在Python中搜索二维数组

时间:2013-02-01 00:58:46

标签: python arrays search

我希望能够通过Python给出两个或更多参数,从大型数据集(9M行,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

给出示例参数:

  • 第二列必须等于2,
  • 第三栏必须在a 范围从4到15

我应该获得:

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,因为它非常易于使用和快速部署。

我的文件是在大约4分钟内通过sqlite3中的导入功能加载的。

我在第二和第三列做了一个索引,以便在检索信息时加快这个过程。

查询是通过Python完成的,模块为“sqlite3”。

这样,方式更快!

1 个答案:

答案 0 :(得分:1)

我几乎可以使用(未​​经测试):

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
相关问题