[英]Pandas CSV Move first row to header row
我有这张表,我使用这段代码导出到 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 栏 |
---|---|---|
时间 | 缓冲区TF2 | 缓冲区TF3 |
12/12/2022 | 10 | 150 |
我想删除第 1、2、3 列并用 BufFT2 和 BufFT3 替换标题
试过这个:
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:]
不知何故它不会工作,我真的不需要替换数据框中的标题,在 csv 中具有正确的标题更重要。
谢谢!
您可以尝试重命名:
df = df.rename(columns=df.iloc[0]).drop(df.index[0])
加载输入文件时,您可以指定将哪一行用作标题
pd.read_csv(inputfile,header=1) # this will use the 2nd row in the file as column titles
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.