如何将pandas.DataFrame写入具有自定义标头的csv文件?

编程入门 行业动态 更新时间:2024-10-27 00:31:31
本文介绍了如何将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文件?

本文发布于:2023-11-05 21:22:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561894.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   如何将   文件   DataFrame   pandas

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!