[英]Search in two dimensional array in Python
我希望能够通过Python给定两个或多个参数来检索大型数据集(900万行,1.4 GB)中的特定行。
例如,从该数据集中:
ID1 2 10 2 2 1 2 2 2 2 2 1
ID2 10 12 2 2 2 2 2 2 2 1 2
ID3 2 22 0 1 0 0 0 0 0 1 2
ID4 14 45 0 0 0 0 1 0 0 1 1
ID5 2 8 1 1 1 1 1 1 1 1 2
给定示例参数:
我应该获得:
ID1 2 10 2 2 1 2 2 2 2 2 1
ID5 2 8 1 1 1 1 1 1 1 1 2
问题是我不知道如何在Python中的二维数组上有效地执行这些操作。
这是我尝试的:
line_list = []
# Loading of the whole file in memory
for line in file:
line_list.append(line)
# set conditions
i = 2
start_range = 4
end_range = 15
# Iteration through the loaded list and split for each column
for index in data_list:
data = index.strip().split()
# now test if the current line matches with conditions
if(data[1] == i and data[2] >= start_range and data[2] <= end_range):
print str(data)
我想执行此过程很多次,但我的方法确实很慢,即使将数据文件加载到内存中也是如此。
我正在考虑使用numpy数组,但是我不知道如何在给定条件的情况下检索行。
谢谢你的帮助 !
如建议的那样,我使用了关系数据库系统。 我选择Sqlite3是因为它易于使用且部署迅速。
我的文件是通过sqlite3中的导入功能加载的,大约需要4分钟。
我在第二和第三列上做了索引,以加快检索信息时的过程。
该查询是通过Python使用模块“ sqlite3”完成的。
那是方法,方法更快!
我几乎会去买(未经测试)的东西:
with open('somefile') as fin:
rows = (line.split() for line in fin)
take = (row for row in rows if int(row[1] == 2) and 4 <= int(row[2]) <= 15)
# data = list(take)
for row in take:
pass # do something
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.