简体   繁体   English

如何使用自定义标头将pandas.DataFrame写入csv文件?

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

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'] . 我想将df写入csv文件,但不使用列['a', 'b'] The first line is my custom string and the rest are the content of df.values . 第一行是我的自定义字符串,其余的是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? 我可以使用熊猫吗?还是必须手动循环浏览内容并写入文件?

You can first create a csv file with the custom text in the first line, and then append the dataframe to it. 您可以首先在第一行中使用自定义文本创建一个csv文件,然后数据框附加到该文件。

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)

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')

Improving over @Divyanshu Srivastava answer : 通过@Divyanshu Srivastava改善答案

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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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