How to write a pandas.DataFrame to csv file with custom header?

耗尽温柔 提交于 2021-01-27 17:24:14

问题


I have a dataframe

import pandas as pd
df = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b'])

I want to write df to a csv file but not using the columns ['a', 'b']. The first line is my custom string and the rest are the content of df.values. For example:

numrows numcols note
1 2
3 4

Can I do this with pandas or I have to manually loop through the content and write to file?


回答1:


You can first create a csv file with the custom text in the first line, and then append the dataframe to it.

with open('file.csv', 'a') as file:
    file.write('Custom String\n')
    df.to_csv(file, header=False, index=False)

Also, see this post.

So, in your case, just use this

with open('file.csv', 'a') as file:
    file.write('numrows numcols note\n')
    df.to_csv(file, header=False, index=False)



回答2:


Improving over @Divyanshu Srivastava answer:

Not that it matters a lot, but no need for keeping open files:

with open(file_path, 'w') as f:
     f.write('Custom String\n')

df.to_csv(file_path, header=False, mode="a")



回答3:


First write custom string and then all data without columns in append mode:

file = 'file.csv'
pd.DataFrame(columns=['numrows numcols note']).to_csv(file, index=False)
df.to_csv(file, header=None, index=False, mode='a')


来源:https://stackoverflow.com/questions/56166681/how-to-write-a-pandas-dataframe-to-csv-file-with-custom-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!