从numpy数组中选择所需的数据

时间:2013-12-18 15:07:49

标签: python numpy

想要选择1到4之间的数据,并将其他数据转换为np.nan 但解决方案是什么?

import numpy as np
data = np.array([1,2,3,4,5])
selected = np.where(1<data<4, data, np.nan)
print (selected)

Traceback (most recent call last):
  File "C:/Users/fe/Desktop/t.py", line 3, in <module>
    selected = np.where(1<data<4, data, np.nan)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

1 个答案:

答案 0 :(得分:4)

你非常接近,你只需要一种不同的方式来选择data中的相关指数。尝试:

>>> selected = np.where((data < 4) & (data > 1), data, np.nan)
>>> selected
array([ nan,   2.,   3.,  nan,  nan])

(data < 4) & (data > 1)找到data的{​​{1}}和< 4的索引。