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

标签 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()

最佳答案

你已经非常接近了,你只需要一种不同的方式来选择 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/

相关文章:

python - 在python中使用numpy.linalg.eig后对特征值和相关特征向量进行排序

python - 使用 python 和 xpath 进行抓取

python - 3D 矩阵的 Numpy 排列

python - Numpy 逐 block 减少操作

python 网络x : simple way to get all simple paths from root to leaf

python - 将字符串附加到 numpy ndarray

python - 在 'date' 上合并 pandas 中的数据帧仅合并 header

python - 数据库异常后 SQLAlchemy 回滚中的错误?

python - 我如何知道有多少映射器和缩减器正在运行?

python - 在 Python 中生成随机向量