简体   繁体   中英

Pandas CSV Move first row to header row

I have this table which i export to CSV Using this code:

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)

While exporting this, my result is:

column 1 column 2 column 3
time BufTF2 BufTF3
12/12/2022 10 150

I want to get rid of column 1,2,3 and replace the header with BufFT2 and BufFT3

Tried this:

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

And This:

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

Somehow it wont work, I not realy in need to replace the headers in the dataframe having the right headers in csv is more important.

Thanks!

You can try rename:

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

when loading the input file you can specify which row to use as the header

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM