【问题标题】:Find indexes by numpy where [duplicate]通过 numpy where [重复]查找索引
【发布时间】:2016-12-21 15:28:12
【问题描述】:

我有 numpy 数组列表:

x = ["A", "A", "B", "A", "C", "D", "B"] 

为了查找"A" 的索引,我使用np.where(x == "A"),它工作正常。 如何找到"A""B" 的索引?

我用过:

np.where(x == ["A", "B"]) 
np.where(x in ["A", "B"])
np.where(x == any(["A", "B"])) 

但这对我没有帮助。

【问题讨论】:

  • Divakar - 您的副本缺少接受的答案,即使用逻辑或掩码的答案。对我来说,这看起来不像是一个好的复制品。 :)
  • 我刚刚注意到另一个可能的duplicate,对于这样的情况,np.in1d(另一个副本中的接受答案)可能使用这里给出的logical_or 答案。查看in1d 的代码。 stackoverflow.com/a/38924371/901925

标签: python numpy where


【解决方案1】:

使用 |np_logical_or 进行元素 OR:

x = np.array(x)
np.where((x=='A') | (x=='B'))
Out: (array([0, 1, 2, 3, 6], dtype=int64),)

np.where(np.logical_or(x=='A', x=='B'))
Out: (array([0, 1, 2, 3, 6], dtype=int64),)

【讨论】:

  • 如果我有很大的条件,即 x=='A', x=='B', x=='C', x=='D'。我该如何使用列表呢?像 x == ['A', 'B', 'C', 'D'] 的东西?
  • 你可以使用in1d:np.in1d(x, ['A', 'B', 'C', 'D'])(这将是np.where中的条件)
猜你喜欢
  • 1970-01-01
  • 2017-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-20
相关资源
最近更新 更多