用 pandas 在CSV文件中写评论 [英] Write comments in CSV file with pandas
本文介绍了用 pandas 在CSV文件中写评论的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在用pandas
创建的CSV文件中写一些注释.我没有在标准csv
模块中的DataFrame.to_csv
中找到任何选项(即使read_csv
可以跳过注释).我可以打开文件,写注释(以#
开头的行),然后将其传递给to_csv
.有没有更好的选择?
I would like to write some comments in my CSV file created with pandas
. I haven't found any option for this in DataFrame.to_csv
(even though read_csv
can skip comments) neither in the standard csv
module. I can open the file, write the comments (line starting with #
) and then pass it to to_csv
. Does any body have a better option?
推荐答案
df.to_csv
接受文件对象.因此,您可以在a
模式下打开文件,编写注释并将其传递到数据框to_csv函数.
df.to_csv
accepts a file object. So you can open a file in a
mode, write you comments and pass it to the dataframe to_csv function.
例如:
In [36]: df = pd.DataFrame({'a':[1,2,3], 'b':[1,2,3]})
In [37]: f = open('foo', 'a')
In [38]: f.write('# My awesome comment\n')
In [39]: f.write('# Here is another one\n')
In [40]: df.to_csv(f)
In [41]: f.close()
In [42]: more foo
# My awesome comment
# Here is another one
,a,b
0,1,1
1,2,2
2,3,3
这篇关于用 pandas 在CSV文件中写评论的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文