gpt4 book ai didi

python - 使用 pandas 在 CSV 文件中写入注释

转载 作者:行者123 更新时间:2023-12-03 03:22:15 24 4
gpt4 key购买 nike

我想在使用 pandas 创建的 CSV 文件中写入一些注释。我在 DataFrame.to_csv 中没有找到任何选项(尽管 read_csv 可以跳过注释),在标准 csv 模块中也没有找到任何选项。我可以打开文件,写入注释(以 # 开头的行),然后将其传递给 to_csv。有谁有更好的选择吗?

最佳答案

df.to_csv 接受文件对象。因此,您可以在 a 模式下打开文件,编写注释并将其传递给数据帧 to_csv 函数。

例如:

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

关于python - 使用 pandas 在 CSV 文件中写入注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29233496/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com