【问题标题】:Extract and then map a column in a 2D numpy array提取并映射 2D numpy 数组中的列
【发布时间】:2021-04-21 16:22:57
【问题描述】:

我正在学习 numpy...

我有一个像这样的二维数组:

myArray = np.array([['0','1'], ['0','1'], ['1','0'], ['1','0']])

我还得到了一个 columnIndex(例如:1

所以我需要提取列并且对于每个元素,如果是“0”则返回“a”,如果是“1”则返回“b”。

myArray[:, columnIndex]
> ['1' '1' '0' '0']

然后

f = lambda x: 'a' if x is '0' else 'b'
f(selected)
> ['1' '1' '0' '0']

但我期待

> ['b', 'b', 'a', 'a']

我最初尝试f = lambda x: 'a' if x == '0' else 'b'并得到了

ValueError:具有多个元素的数组的真值不明确。使用 a.any() 或 a.all()

为什么会这样?如何干净地提取和转换 2d numpy 数组中的列?

【问题讨论】:

  • 你为什么期望一个二维数组?你的预期结果['b', 'b', 'a', 'a'] 是 1d。

标签: python arrays numpy


【解决方案1】:

您不能在 if 子句中使用数组作为条件,这就是您收到错误的原因

ValueError:具有多个元素的数组的真值不明确。使用 a.any() 或 a.all()

selected 是什么也不太清楚,我猜是myArray[:, columnIndex]

您可以使用list comprehension

import numpy as np

column_index = 1
myArray = np.array([['0','1'], ['0','1'], ['1','0'], ['1','0']])
selected = myArray[:, column_index]

result = ['a' if x == '0' else 'b' for x in selected]
print(result) # ['b' 'b' 'a' 'a']

我更喜欢使用numpy.where,根据条件选择两个选项之一:

result = np.where(selected == '0', 'a', 'b')
print(result) # ['b' 'b' 'a' 'a']

对于这里给出的小例子,列表理解更快,但我希望 numpy 解决方案对于更大的数组更快。请注意,numpy.where 将返回 numpy.ndarray 而不是列表。

【讨论】:

  • 很好的答案!--
  • 感谢您的友好解释。你是对的,selected = myArray[:, columnIndex]。现在我学会了“列表理解”和 numpy where 。太棒了!
  • @nacho4d 很高兴。列表推导简洁而强大,而且非常有趣!我还添加了文档链接。
【解决方案2】:

发生这种情况是因为f 没有单独应用于此处的元素,而是应用于整个数组。您缺少的是对mapother comparable approaches 的调用。

【讨论】:

    猜你喜欢
    • 2011-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-07
    • 1970-01-01
    • 2011-10-13
    相关资源
    最近更新 更多