【问题标题】:Python search through a text file using a Dataframe columnPython 使用 Dataframe 列搜索文本文件
【发布时间】:2022-01-01 11:37:55
【问题描述】:

我有一个非常大的文本文件(超过 1100 万条记录),“;”分隔,三列。我有一个 Pandas 数据框(单列),其中包含我需要在文本文件中搜索的值。 问题是我无法将大文本文件加载到内存中。

我已经嵌套了 for 循环,这需要很长时间。在文本文件的每一行中搜索每一列值。这就是我所拥有的:

import os
import pandas as pd

os.chdir('D:\\AllFiles\\Projects')
mainPath = os.getcwd()

inputFile = 'A.txt'
inputPath = os.path.join(mainPath, inputFile)
input_data = open(inputPath, 'r')

outputFile = 'A_A.csv'
outputPath = os.path.join(mainPath, outputFile)
output_data = open(outputPath,'w')


#  input file name and location
actFile = 'SingleColList.txt'
actPath = os.path.join(mainPath, actFile)

#   Read the cleaned data in a dataframe 
act_df = pd.read_csv(actPath,header=0)

with input_data as f:
    for num, line in enumerate(f, 1):
        for index, row in act_df.iterrows():
            if row['col1'] in line:
                output_data.write( line ) 

input_data.close()
output_data.close()

print('Done!')

我可以使用更快的东西吗?

在此先感谢您的帮助。

【问题讨论】:

  • 更快/内存效率/延迟加载库的选项:dask、pyspark、koalas。这些软件包可能会也可能不会超出您的记忆。另一种常见的方法是将数据集拆分/分区为多个较小的文件,以便可以将它们读入内存并单独处理(并且可能并行处理,这基本上是上述库的目标)。
  • read_csv('A.txt') 不允许您读取所有 11 M 条记录?您还可以设置一个块大小来迭代。另外,请查看pandas.pydata.org/docs/reference/api/…。您可能不必迭代,而是使用正则表达式??? s1.str.contains('house|dog', regex=True) 您可以获取所有搜索词并创建一个由管道分隔的字符串。很难确切地说这是否适合您的用例

标签: python pandas dataframe text iteration


【解决方案1】:

这里有一些可能有帮助的例子

设置一个名为“A.txt”的简单文件

a;b;c
cat;dog;mouse
mouse;moose;mice
apple;pie;good
no;its;not
what;is;this
three;word;sentences
great;good;best
stop;doing;this
or;doing;that

创建搜索词列表

mylist = ['ca', 'why', 'help', 'cat', 'is', 'three', 'best']

选项1:读取文件并解析;然后按列搜索。不要认为这是一个好的选择,但出于比较目的而显示。

In [33]: df = pd.read_csv('A.txt', sep=';')
    ...: df[df['a'].str.contains('|'.join(mylist), regex=True)]
Out[33]:
       a     b          c
0    cat   dog      mouse
5  three  word  sentences

选项 2:读取文件,不解析因此搜索整行

In [34]: df = pd.read_csv('A.txt', header=0)
    ...: df[df['a;b;c'].str.contains('|'.join(mylist), regex=True)]
Out[34]:
                  a;b;c
0         cat;dog;mouse
4          what;is;this
5  three;word;sentences
6       great;good;best
7       stop;doing;this

选项 3:使用 chunksize 并使用选项 1 或 2 或在每次迭代期间您需要的任何内容

In [35]: iterator = pd.read_csv('A.txt', header=0, chunksize=2)
    ...: for i in iterator:
    ...:     print(i)
    ...:
              a;b;c
0     cat;dog;mouse
1  mouse;moose;mice
            a;b;c
2  apple;pie;good
3      no;its;not
                  a;b;c
4          what;is;this
5  three;word;sentences
             a;b;c
6  great;good;best
7  stop;doing;this
           a;b;c
8  or;doing;that

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-13
    • 2012-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多