我有一个很大的文本文件(300000000 行),但它充满了不需要的数据,我想将其删除。这些数据是包含字符串“0000e”的数据。
我尝试过:
f=pd.read_csv('File.txt', skiprows=139, header=None, index_col=False)
f=f.iloc[:,0]
f1=f[f.str.contains("0000e")==False]
和
f=pd.read_csv('file.txt', skiprows=139, header=None, index_col=False, chunksize=50)
dfs = pd.concat([x[x[0].str.endswith('000e')==False] for x in f])
但是它相当长,有没有更快的方法来跳过某些包含特定字符串的行?也许与 na_values 一起?
最佳答案
我更喜欢你的第一次尝试,因为它绝对更具可读性,因为你的第二行有 x 并且我不知道它们指的是什么。
也就是说,使用 memory_map=True
将提高性能如文档中所述,您还可以通过删除第二行并访问该列来获得额外的优势在同一行中创建 df。最后,用 ~...
替换检查 ...==False
可能会带来一些好处。因为 ~
是逻辑 not
,但您需要过滤掉所有 NaN
值,否则会出现错误。幸运的是,Series.str.contains
接受 na
属性,将给定函数应用于 NaN
值。
import pandas as pd
df = pd.read_csv('File.txt', memory_map=True, header=None, index_col=False).iloc[:,0]
df1 = df[~df.str.contains("test", na=False)]
#if you want to also skip NaN rows use the below statement
df1 = df[~df.str.contains("test", na=False)].dropna()
或者,使用 csv
执行此操作要快得多,即使您决定随后将其加载到 pandas 中。我不知道您的数据是什么样的,但我使用包含 3 列和 100 行的 csv
文件对这些数据进行了测试,性能提高了大约 9 倍。这可能与您的结果无关,但如果我是您,这绝对是我会选择的方法。
from csv import reader
filter = '0000e' #so we aren't making a new string every iteration
with open('File.txt', 'r') as f:
df = pd.DataFrame(first for first, *_ in reader(f) if filter not in first)
#if you want to skip NaN rows
...(first for first, *_ in reader(f) if not first and filter not in first)
#take note this also skips empty strings, use if first is not None for only skipping NaN values
关于python - Pandas:读取文件时跳过包含特定字符串的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55404520/