用 pandas 在 CSV 文件中写评论

Write comments in CSV file with pandas

我想在用 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

另一种方法@Vor 的解决方案是先将注释写入文件,然后使用mode='a'to_csv() 将数据框的内容添加到同一个文件中。根据我的基准测试(如下),这大约需要以附加模式打开文件、添加注释然后将文件处理程序传递给 pandas(根据@Vor 的回答)。考虑到这是 pandas 在内部执行的操作(DataFrame.to_csv() 调用 CSVFormatter.save(),它通过 open() 使用 _get_handles() to read in the file,所以类似的时间安排是有意义的。

另外,通过 with 语句处理文件 IO 很方便,它确保打开的文件在您完成处理后关闭并离开 with 语句。请参阅下面基准测试中的示例。

读入测试数据

import pandas as pd
# Read in the iris data frame from the seaborn GitHub location
iris = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')
# Create a bigger data frame
while iris.shape[0] < 100000:
    iris = iris.append(iris)
# `iris.shape` is now (153600, 5)

1。附加相同的文件处理程序

%%timeit -n 5 -r 5

# Open a file in append mode to add the comment
# Then pass the file handle to pandas
with open('test1.csv', 'a') as f:
    f.write('# This is my comment\n')
    iris.to_csv(f)
972 ms ± 31.9 ms per loop (mean ± std. dev. of 5 runs, 5 loops each)

2。使用 to_csv(mode='a')

重新打开文件
%%timeit -n 5 -r 5

# Open a file in write mode to add the comment
# Then close the file and reopen it with pandas in append mode
with open('test2.csv', 'w') as f:
    f.write('# This is my comment\n')
iris.to_csv('test2.csv', mode='a')
949 ms ± 19.3 ms per loop (mean ± std. dev. of 5 runs, 5 loops each)