【问题标题】:Pandas export data to CSV and make first row headersPandas 将数据导出到 CSV 并制作第一行标题
【发布时间】:2023-02-13 22:24:35
【问题描述】:

我有这张表,我使用这段代码导出到 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 | |:---- |:------: | -----: | | FT1 | FT2 | FT3 | | 12 | 8 | 3 | 我想去掉第 1、2、3 列并用 FT2 和 FT3 替换标题

试过这个:

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.iloc[1:] 以及“不知何故无法正常工作”究竟是什么意思?到底是什么问题。显而易见的是,您在使用 to_csv 之前进行了 df 转换,对吗?你能提供样本数据吗?例如df.iloc[:5].to_dict()
  • 只需使用偏移量导出 df.iloc[1:].to_csv(r'C:\****\Exports\exportMMA.csv', index=False)

标签: python pandas csv export


【解决方案1】:

您可以在将 DataFrame 写入 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()

# Changing the column names
df.columns = ['FT2', 'FT3']

# Writing the DataFrame to a CSV file
df.to_csv(r'C:****ExportsexportMMA.csv', index=False, header=True)

to_csv 方法中的 header 参数决定是否将列名写入 CSV 文件。在这种情况下,它被设置为 True 以便写入列名。

【讨论】:

    猜你喜欢
    • 2014-08-13
    • 2021-10-17
    • 1970-01-01
    • 1970-01-01
    • 2021-05-28
    • 2019-06-15
    • 1970-01-01
    • 2020-09-29
    • 1970-01-01
    相关资源
    最近更新 更多