Pandas CSV将第一行移到标题行

jexiocij  于 2022-12-15  发布在  其他
关注(0)|答案(2)|浏览(263)

我有这个表,我导出到CSV使用此代码:

df['time'] = df['time'].astype("datetime64").dt.date
df = df.set_index("time")
df = df.groupby(df.index).agg(['min', 'max', 'mean'])
df = df.reset_index()
df = df.to_csv(r'C:\****\Exports\exportMMA.csv', index=False)

在导出此文件时,我的结果是:
| 栏1|第2栏|第3栏|
| - ------|- ------|- ------|
| 时间|缓冲因子2|缓冲因子3|
| 2022年12月12日|十个|一百五十|
我想去掉第1、2、3列,并将标题替换为BufFT 2和BufFT 3
尝试了以下操作:

new_header = df.iloc[0] #grab the first row for the header
df = df[1:] #take the data less the header row
df.columns = new_header #set the header row as the df header

还有这个:

df.columns = df.iloc[0]
df = df[1:]

不知何故,它不会工作,我不真正需要更换标题的 Dataframe 有正确的标题在csv是更重要的。
谢谢!

3bygqnnd

3bygqnnd1#

您可以尝试重命名:

df = df.rename(columns=df.iloc[0]).drop(df.index[0])
balp4ylt

balp4ylt2#

装入输入文件时,可以指定要用作标题的行

pd.read_csv(inputfile,header=1)  # this will use the 2nd row in the file as column titles

相关问题