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

4 投票
3 回答
3414 浏览
提问于 2025-04-15 16:49

我在寻找一种高效的方法来压缩一个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

如果你想要一个只用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']])

如果你觉得这个方法不够高效,我建议你进行一些基准测试,这样你就能确认自己在努力让它更高效时,花的时间是值得的。

1

压缩一个numpy数组最好的方法是使用pytables。它是处理大量数字数据的标准工具。

import tables as t
hdf5_file = t.openFile('outfile.hdf5')
hdf5_file.createArray ......
hdf5_file.close()
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]

撰写回答