如何在python数据框架中的列和行之间转换?
情景1 原始数据帧: a b c d e f g 新数据帧:如何在python数据框架中的列和行之间转换?,python,dataframe,Python,Dataframe,情景1 原始数据帧: a b c d e f g 新数据帧: a b c d e f g 情景2 原始数据帧: g f e d c b a 新数据帧: a b c d e f g 我的问题是如何执行上述转换?请尝试以下操作: import pandas as pd df = pd.DataFrame(columns=list('abcdefg')) df_new = pd.DataFrame([col for col in df.columns], columns=['column_to_ro
a
b
c
d
e
f
g 情景2 原始数据帧: g f e d c b a 新数据帧:
a
b
c
d
e
f
g 我的问题是如何执行上述转换?请尝试以下操作:
import pandas as pd
df = pd.DataFrame(columns=list('abcdefg'))
df_new = pd.DataFrame([col for col in df.columns], columns=['column_to_rows'])
print(df_new)
只需将“.T”添加到数据帧中
pd.DataFrame(['a','b','c', 'd', 'e', 'f', 'g'])
Out[99]:
0
0 a
1 b
2 c
3 d
4 e
5 f
6 g
pd.DataFrame(['a','b','c', 'd', 'e', 'f', 'g']).T
Out[100]:
0 1 2 3 4 5 6
0 a b c d e f g
使用转置方法
df.T
,其中df
是您的数据帧。