想要选择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()
最佳答案
你已经非常接近了,你只需要一种不同的方式来选择 data
中的相关索引。尝试:
>>> selected = np.where((data < 4) & (data > 1), data, np.nan)
>>> selected
array([ nan, 2., 3., nan, nan])
(data < 4) & (data > 1)
查找 data
的索引两者都是 < 4
和>1
.
关于python - 从numpy数组中选择所需的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20661629/