我正在尝试读取一个非常大的文本文件(.dat文件)-太大而无法完整打开-但我对整个内容(只是很小的一部分)不感兴趣。
真实的文本文件有32列,行数未知。我只对列nr 15中的值小于40且列21中的值在10 - 25之间的行感兴趣。有没有办法在python中打开和加载文件时指定这些约束,这样我就可以避免在我不关心的内容上浪费内存?
下面是一个示例:
假设我们有一个包含100个数据(25行4列)的文件,我们只想读取行(整行!)其中列NR2中的值小于40,并且列NR4中的值在10 - 25之间。如果不先加载完整的文件,我们如何做到这一点呢?
import numpy as np
# Create some examplary fake data for the text file:
textfile_content = np.random.randint(100, size=100).reshape(25,4)
print(textfile_content)
# Save text file:
np.savetxt('file.dat', textfile_content, fmt='%10.5e')
我能用谷歌搜索到的最接近的方法是:Reading specific lines only (Python)
但这并不能完全解决我的问题,因为这个人想提取完整的列,这些列是通过它们的列号而不是特定的数据值来预定义的。
发布于 2018-06-11 02:40:47
您可以使用dask.dataframe
通过筛选器延迟加载数据。在内部,这个库通过分块来工作。它只是对用户隐藏了分块,并利用Pandas语法来无缝地使用。
import pandas as pd
import numpy as np
import dask.dataframe as dd
# file.csv
# 1 2 3 4
# 5 6 7 8
# ....
# 33 34 35 36
# 37 38 39 40
# read file - LAZY
df = dd.read_csv(r'C:\Temp\file.csv', header=None, sep=' ',
names=['col1', 'col2', 'col3', 'col4'])
# filter file - LAZY
df = df[df['col4'].between(10, 25)]
# apply computations and extract to pandas dataframe
df = df.compute()
# extract numpy array from pandas dataframe
arr = df.values
print(arr)
array([[ 9, 10, 11, 12],
[13, 14, 15, 16],
[17, 18, 19, 20],
[21, 22, 23, 24]], dtype=int64)
https://stackoverflow.com/questions/50785017
复制相似问题