python - 是否可以使用 read_csv 只读取特定行?

标签 python csv pandas

我有一个如下所示的 csv 文件:

TEST  
2012-05-01 00:00:00.203 ON 1  
2012-05-01 00:00:11.203 OFF 0  
2012-05-01 00:00:22.203 ON 1  
2012-05-01 00:00:33.203 OFF 0  
2012-05-01 00:00:44.203 OFF 0  
TEST  
2012-05-02 00:00:00.203 OFF 0  
2012-05-02 00:00:11.203 OFF 0  
2012-05-02 00:00:22.203 OFF 0  
2012-05-02 00:00:33.203 OFF 0  
2012-05-02 00:00:44.203 ON 1  
2012-05-02 00:00:55.203 OFF 0  

并且不能去掉 "TEST" 字符串。

是否可以检查一行是否以日期开头并只读取以日期开头的行?

最佳答案

from cStringIO import StringIO
import pandas

s = StringIO()
with open('file.csv') as f:
    for line in f:
        if not line.startswith('TEST'):
            s.write(line)
s.seek(0) # "rewind" to the beginning of the StringIO object

pandas.read_csv(s) # with further parameters…

关于python - 是否可以使用 read_csv 只读取特定行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10717504/

相关文章:

python - 如何在 python 中将矩阵写入 csv 文件并在第一行和第一列中添加静态标题?

java - 使用 apache commons 获取 CSV 文件头

python - 从多索引 pandas 系列创建 1 列数据框

python - 使用 Python 从 JSON API 获取特定值并插入到 Postgresql 中

python - 在 Python 中复制二维数组的最快方法是什么?

python - 如何在 Pycharm 中使用 Pandas

python - 如何使用 numpy 数组最大限度地提高效率?

c# - 在 C# 中读取 CSV 文件

python - Pandas DF.output 写入列(当前数据全部写入一行或一列)

python - 在 Python 中过滤数据集中的 'contains value'