【问题标题】:How to use with open to filter datafiles in python and create new file?如何使用 open 在 python 中过滤数据文件并创建新文件?
【发布时间】:2021-06-26 10:59:01
【问题描述】:

我有巨大的 csv,我尝试使用 with open 过滤数据。

我知道我可以在命令行上使用 FINDSTR,但我想使用 python 创建一个过滤的新文件,或者我想创建一个 pandas 数据框作为输出。

这是我的代码:

outfile = open('my_file2.csv', 'a')
with open('my_file1.csv', 'r') as f:
 for lines in f:
         if '31/10/2018' in lines:
            print(lines)  
         outfile.write(lines)

问题是生成的输出文件是=输入文件,没有过滤器(和文件大小一样)

谢谢大家

【问题讨论】:

  • 接近一个错字:你只需要缩进outfile.write(lines)print(lines)一样。

标签: python pandas csv bigdata data-warehouse


【解决方案1】:

您的代码的问题是最后一行的缩进。它应该在 if 语句中,因此只有包含 '31/10/2018' 的行才会被写入。

outfile = open('my_file2.csv', 'a')
with open('my_file1.csv', 'r') as f:
 for lines in f:
         if '31/10/2018' in lines:
            print(lines)  
            outfile.write(lines)

要使用 Pandas 进行过滤并创建 DataFrame,请执行以下操作:

import pandas as pd
import datetime

# I assume here that the date is in a seperate column, named 'Date'
df = pd.read_csv('my_file1.csv', parse_dates=['Date']) 

# Filter on October 31st 2018
df_filter = df[df['Date'].dt.date == datetime.date(2018, 10, 31)]

# Output to csv
df_filter.to_csv('my_file2.csv', index=False)

(对于非常大的 csv,请查看 pd.read_csv() 参数 'chunksize')

要使用with open(....) as f:,您可以执行以下操作:

import pandas as pd

filtered_list = []
with open('my_file1.csv', 'r') as f:
    for lines in f:
        if '31/10/2018' in lines:
            print(lines)
            # Split line by comma into list
            line_data = lines.split(',')
            filtered_list.append(line_data)

# Convert to dataframe and export as csv
df = pd.DataFrame(filtered_list)
df_filter.to_csv('my_file2.csv', index=False)

【讨论】:

  • 谢谢。您知道如何在不创建新文件的情况下在 pandas 数据框中使用过滤后的数据吗?或者如何使用我的代码按列过滤数据?
  • 好的,谢谢,但我的意思是输出: with open('my_file1.csv', 'r') as f: for lines in f: if '31/10/2018' in lines: print (行)
  • 如果您仍然要使用 Pandas,为什么要这样做?还是'my_file1.csv' 除了标题和数据行之外还包含其他行?
  • 因为文件太大,我想只分析用 print(lines) 得到的输出。我不知道为什么,但输出文件(my_file2.csv)缺少 10 行
  • 见上面的解决方案
猜你喜欢
  • 2012-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-22
  • 2014-04-25
  • 2017-05-09
  • 2021-09-14
  • 1970-01-01
相关资源
最近更新 更多