首页 > 解决方案 > 数据框将标题行转换为熊猫行

问题描述

有一个带有值的df

东风:

165  156  1    test    greater 56gsa
-------------------------------------
spin 201  2    normal  lesser  12asgs
pine 202  3    fast    greater 5sasgs

所需输出:

0     1   2     3        4       5
-------------------------------------
165  156  1    test    greater 56gsa
spin 201  2    normal  lesser  12asgs
pine 202  3    fast    greater 5sasgs

标签: pythonpandasdataframe

解决方案


如果 DataFrame 是从文件创建的,那么header=None参数就是你的朋友:

df = pd.read_csv(file, header=None)

如果不是,则将列转换为一行DataFrame并转换DataFrame.append为原始数据:

df = df.columns.to_frame().T.append(df, ignore_index=True)
df.columns = range(len(df.columns))
print (df)
      0    1  2       3        4       5
0   165  156  1    test  greater   56gsa
1  spin  201  2  normal   lesser  12asgs
2  pine  202  3    fast  greater  5sasgs

推荐阅读