将标题转置为列而不是索引的 pandas 数据帧



当我转置数据帧时,默认情况下将标头视为"索引"。但我希望它是一列而不是索引。我该如何实现这一点?

import pandas as pd
dict = {'col-a': [97, 98, 99],
'col-b': [34, 35, 36],
'col-c': [24, 25, 26]}
df = pd.DataFrame(dict)
print(df.T)
0   1   2
col-a  97  98  99
col-b  34  35  36
col-c  24  25  26

期望输出:

0   1   2   3
0  col-a  97  98  99
1  col-b  34  35  36
2  col-c  24  25  26

尝试使用reset_indexT

df=df.T.reset_index()
print(df)

或:

df.T.reset_index(inplace=True)
print(df)

两个输出:

index   0   1   2
0  col-a  97  98  99
1  col-b  34  35  36
2  col-c  24  25  26

如果关心列名,请将以下内容添加到代码中:

df.columns=range(4)

或:

it=iter(range(4))
df=df.rename(columns=lambda x: next(it))

或者如果不知道列数:

df.columns=range(len(df.columns))

或:

it=iter(range(len(df.columns)))
df=df.rename(columns=lambda x: next(it))

所有输出:

0   1   2   3
0  col-a  97  98  99
1  col-b  34  35  36
2  col-c  24  25  26

使用reset_index,然后设置默认列名称:

df1 = df.T.reset_index()
df1.columns = np.arange(len(df1.columns))
print (df1)
0   1   2   3
0  col-a  97  98  99
1  col-b  34  35  36
2  col-c  24  25  26

另一种解决方案:

print (df.rename_axis(0, axis=1).rename(lambda x: x + 1).T.reset_index())
#alternative
#print (df.T.rename_axis(0).rename(columns = lambda x: x + 1).reset_index())
0   1   2   3
0  col-a  97  98  99
1  col-b  34  35  36
2  col-c  24  25  26

最新更新