【问题标题】:How do we extract arrays from a nested numpy array based on conditions on the subarrays?我们如何根据子数组上的条件从嵌套的 numpy 数组中提取数组?
【发布时间】:2019-07-01 16:28:15
【问题描述】:

我有一个输出,它是一个嵌套的 numpy 数组。每个子数组都有 10 个浮点值,我想从这个“更大”数组中提取那些在特定索引处具有最大值的子数组。 编辑:(为清楚起见进行了编辑) 嵌套数组示例 -

[[1 0 0 0] [1 0 0 0] [0 0 1 0] [1 0 0 0] [0 1 0 0] [0 0.99 0 0]

需要的输出 [[0 1 0 0] [0 0.99 0 0]](本例我们取索引为1)

我想提取那些在索引 0,1,2 等处的值最高的子数组。所以这里的条件是提取索引 1 处的值(例如)为最大值的所有子数组。

【问题讨论】:

  • 我已经编辑了一个更清晰的例子。
  • 通常我们将您的数组描述为多维数组,在本例中为形状为 (6,4) 的 2d。

标签: python arrays numpy


【解决方案1】:

这是一种方法:

example = [[8, 5], [8,7], [5.6,1], [7, 9]]

# You choose which specific index you want tha max value
max_value_index= 0

# We use a list comprehension to select the corresponding rows
result = [x for x in example if x[max_value_index] == np.max(x)]

输出:

[[8, 5], [8, 7], [5.6, 1]

【讨论】:

  • [column_i] 是做什么的?是否对应索引值?
  • 谢谢@AdityaDas,我忘了像其他人一样重命名它max_value_index
  • 这有效,但它仅适用于值为整数的情况。我们如何使它适用于浮动?
  • 它也适用于我的浮动。您尝试了哪些输入?
  • [[8, 5], [8,7], [5,6],[5.6,1]] 输出也应该包含[5.6,1] 对吧?
【解决方案2】:

因此,据我了解,您有一些 max_index 参数,并且您希望获取最大元素落在该索引处的所有行。为此,您可以说“返回我的数组中该行的 argmax 等于最大索引的所有行”,在 numpy 中是单行:

arr = np.random.randn(100, 10)
max_index = 2
rows_with_max_at_max_index = arr[np.argmax(arr, axis=1) == max_index]  # A (N x 10) array 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-21
    • 2017-03-15
    • 2021-01-24
    • 2022-06-14
    • 1970-01-01
    • 2019-09-16
    • 2018-08-27
    相关资源
    最近更新 更多