压缩numpy数组的有效方法(python)

时间:2009-12-09 00:31:56

标签: python filter numpy compression

我正在寻找一种压缩numpy数组的有效方法。 我有一个数组:dtype=[(name, (np.str_,8), (job, (np.str_,8), (income, np.uint32)](我最喜欢的例子)。

如果我正在做这样的事情:my_array.compress(my_array['income'] > 10000)我正在获得一个只有收入>的新阵列10000,而且很快。

但是如果我想在列表中过滤作业:它不起作用!

my__array.compress(m_y_array['job'] in ['this', 'that'])

错误:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

所以我必须做这样的事情:

np.array([x for x in my_array if x['job'] in ['this', 'that'])

这既丑陋又低效!

你有想法让它变得高效吗?

3 个答案:

答案 0 :(得分:1)

它不如你想要的那么好,但我认为你可以做到:

mask = my_array['job'] == 'this'
for condition in ['that', 'other']:
  mask = numpy.logical_or(mask,my_array['job'] == condition)
selected_array = my_array[mask]

答案 1 :(得分:1)

压缩numpy数组的最佳方法是使用pytables。在处理大量数值数据时,它是事实上的标准。

import tables as t
hdf5_file = t.openFile('outfile.hdf5')
hdf5_file.createArray ......
hdf5_file.close()

答案 2 :(得分:0)

如果你正在寻找一个只有numpy的解决方案,我认为你不会得到它。尽管如此,虽然它有很多工作要做,但要考虑tabular包可能能够以一种不那么“丑陋”的方式做你想做的事情。如果不自己编写C扩展,我不确定你会获得更多的“效率”。

顺便说一句,我认为这对于任何真实案例来说都足够有效且非常适合。

my_array.compress([x in ['this', 'that'] for x in my_array['job']])

作为使这不那么丑陋和更高效的额外步骤,你可能不会在中间有一个硬编码列表,所以我会使用一个集合,因为如果列表有更多,搜索比列表快得多而不是几个项目:

job_set = set(['this', 'that'])
my_array.compress([x in job_set for x in my_array['job']])

如果您认为这不够有效,我会建议您进行基准测试,这样您就可以确信自己花了很多时间来尝试提高效率。