我正在寻找一种压缩 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'])
这既丑陋又低效!
您有提高效率的想法吗?
最佳答案
它没有你想要的那么好,但我认为你可以做到:
mask = my_array['job'] == 'this'
for condition in ['that', 'other']:
mask = numpy.logical_or(mask,my_array['job'] == condition)
selected_array = my_array[mask]
关于python - 压缩 numpy 数组的有效方法(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1870871/