python - 除一个特定值外,如何将 numpy 数组中的所有值替换为零?

标签 python numpy matrix multidimensional-array

我有一个带有“n”个唯一值的二维 numpy 数组。 我想生成一个二进制矩阵,其中所有值都替换为 “零”,我指定的值被分配为“一”。

例如,我有一个数组如下,我想要所有的实例 35 个被分配为“一个”:

array([[12, 35, 12, 26],
       [35, 35, 12, 26]])

我正在尝试获得以下输出:

array([[0, 1, 0, 0],
       [1, 1, 0, 0]])

在 Python 中最有效的方法是什么?

最佳答案

import numpy as np
x = np.array([[12, 35, 12, 26], [35, 35, 12, 26]])
(x == 35).astype(int)

会给你:

array([[0, 1, 0, 0],
       [1, 1, 0, 0]])

numpy 中的 == 运算符执行逐元素比较,将 bool 值转换为整数时,True 编码为 1,False 编码为 0。

关于python - 除一个特定值外,如何将 numpy 数组中的所有值替换为零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48308240/

相关文章:

python - 矩阵A乘以多维矩阵 "matrix-wise?"

python - 同一向量的归一化在两种情况下给出不同的值?

Python numpy loadtxt : reading an empty file into an array with a particular number of columns

algorithm - 在 log(n) 时间内排序的 bool n*n 矩阵中 0 的数量

python - 所选索引的 Pandas Invert Sign

python - Gurobi 线性表达式与常数的乘法

matrix - 如何在 Promela 中创建二维数组?

时间:2019-03-09 标签:c#Battleshipsminigame

python - ValueError : Found array with 0 sample (s) (shape= (0, 1) 而 MinMaxScaler 要求最小值为 1

multidimensional-array - 符号识别,例如 scikit-learn 中的手写数字示例(python)