簡體   English   中英

Pandas CSV 將第一行移動到標題行

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM