如何将pandas.DataFrame写入具有自定义标头的csv文件? [英] How to write a pandas.DataFrame to csv file with custom header?
本文介绍了如何将pandas.DataFrame写入具有自定义标头的csv文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框
import pandas as pd
df = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b'])
我想将 df
写入一个csv文件,但不使用列 ['a','b']
.第一行是我的自定义字符串,其余是 df.values
的内容.例如:
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?
推荐答案
您可以先在第一行中使用自定义文本创建一个csv文件,然后将数据框附加.
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)
此外,请参见此帖子
因此,就您而言,只需使用此
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)
这篇关于如何将pandas.DataFrame写入具有自定义标头的csv文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文