python - numpy:使用 OR 将多个赋值转换为单个赋值

标签 python arrays numpy indexing numpy-ndarray

taxi_modified 是一个二维 ndarray。

下面的代码可以工作,但看起来不符合Python风格:

taxi_modified[taxi_modified[:, 5] == 2, 15] = 1
taxi_modified[taxi_modified[:, 5] == 3, 15] = 1
taxi_modified[taxi_modified[:, 5] == 5, 15] = 1

如果索引 5 处的列是 2、3、 5,则需要将 1 分配给索引 15 处的列。

以下不起作用:

taxi_modified[taxi_modified[:, 5] == 2 | 3 | 5, 15] = 1

最佳答案

您可以使用 np.isin 进行精美索引(NumPy v1.13+),或np.in1d对于旧版本。

这是一个演示:

# example input array
A = np.arange(16).reshape((4, 4))

# calculate Boolean mask for rows
mask = np.isin(A[:, 1], [1, 5, 13])

# assign values, converting mask to integers
A[np.where(mask), 2] = -1

print(A)

array([[ 0,  1, -1,  3],
       [ 4,  5, -1,  7],
       [ 8,  9, 10, 11],
       [12, 13, -1, 15]])

在一行中,可以这样写:

A[np.where(np.isin(A[:, 1], [1, 5, 13])), 2] = -1

关于python - numpy:使用 OR 将多个赋值转换为单个赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52703473/

相关文章:

python - 管道弹出标准错误和标准输出

python - 使用两个不同的 Python 发行版

python - 如何在 Python 中处理一小部分数据?

python - Pandas 的性能应用 vs np.vectorize 从现有列创建新列

python - 从热图数据生成边界框

python - Python Meep 中的 Vector3

php - 带有返回语句的 Foreach 循环

java - 为什么在 Java 1.8 中这样排序

python - OpenGL 中的太阳系,相机位置

python - 根据两个 pandas DataFrame 之间的条件为新列分配值