【问题标题】:Numpy boolean indexing if number is in list如果数字在列表中,则为 Numpy 布尔索引
【发布时间】:2020-03-05 06:05:17
【问题描述】:

我有以下数组:

x = np.array([
    [2, 0],
    [5, 0],
    [1, 0],
    [8, 0],
    [6, 0]])

我了解到您可以使用布尔运算来更改 numpy 数组中的选定值。如果我想将第一个值等于 2、5 或 8 的行的第二列的值更改为 1,我可以执行以下操作:

x[x[:, 0] == 2, 1] = 1
x[x[:, 0] == 5, 1] = 1
x[x[:, 0] == 8, 1] = 1

这会将输出更改为:

[[2 1]
 [5 1]
 [1 0]
 [8 1]
 [6 0]]

如果那是“正常”的 python 代码,我知道我可以做到:

if value in [2, 5, 8]: ...

代替:

if value == 2 or value == 5 or value == 8: ...

对于 numpy 数组是否有这样的简写方式?

【问题讨论】:

标签: python arrays numpy boolean-operations


【解决方案1】:

你可以使用numpy的isin方法:

x[np.isin(x[:, 0], [2, 5, 8]), 1] = 1

【讨论】:

    【解决方案2】:

    您可以将np.isin()np.where() 结合使用:

    x[:,1] = np.where(np.isin(x[:,0], [2,5,8]), 1, 0)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-06
      • 1970-01-01
      • 1970-01-01
      • 2020-03-25
      • 1970-01-01
      • 1970-01-01
      • 2015-05-19
      相关资源
      最近更新 更多