【问题标题】:Numpy python - calculating sum of columns from irregular dimensionNumpy python - 从不规则维度计算列的总和
【发布时间】:2022-12-09 21:37:09
【问题描述】:

我有一个用于分数的多维数组,为此,我需要在 Python 的第 3 级获取每一列的总和。我在用麻木的为达到这个。

import numpy as np

数据是这样的:

score_list = [
    [[1,1,3], [1,2,5]],
    [[2,7,5], [4,1,3]]
]

这应该返回:

[[3 8 8] [5 3 8]]

使用这个正确发生了什么:

sum_array = np_array.sum(axis=0)
print(sum_array)

但是,如果我有这样的不规则形状:

score_list = [
    [[1,1], [1,2,5]],
    [[2,7], [4,1,3]]
]

我希望它返回:

[[3 8] [5 3 8]]

但是,它发出警告,返回值为:

[列表([1, 1, 2, 7]) 列表([1, 2, 5, 4, 1, 3])]

我怎样才能得到预期的结果?

【问题讨论】:

    标签: python numpy multidimensional-array


    【解决方案1】:

    numpy 将尝试将其转换为 nd 数组,这将失败,而是考虑使用 zip 单独传递每个子列表。

    score_list = [
        [[1,1], [1,2,5]],
        [[2,7], [4,1,3]]
    ]
    
    import numpy as np
    res = [np.sum(x,axis=0) for x in zip(*score_list)]
    print(res)
    
    [array([3, 8]), array([5, 3, 8])]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-19
      • 2021-08-17
      • 2012-02-22
      • 1970-01-01
      • 2021-07-20
      • 2018-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多