gpt4 book ai didi

python - 如何计算Python中numpy数组中n个元素的总和?

转载 作者:行者123 更新时间:2023-12-03 00:13:21 28 4
gpt4 key购买 nike

假设我有一个 n x d python 数组,例如a=np.array([[1,2,3],[4,5,6], [7,8,9], [10,11,12], [13,14,15]])

所以在这种情况下 n=5,d=3 并想象我有一些小于或等于 n 的数字 c,我想要计算如下:

独立考虑每一列并计算每个c值的总和;例如如果c=2,则解为

solution=np.array([[1+4, 2+5, 3+6], [7+10,8+11,9+12]])

最后一行被跳过,因为 5 mod 2 = 1,所以我们需要在最后省略一行;

如果 c=1,解将是原始数组,如果例如c=3 解决方案是

solution=np.array([[1+4+7, 2+5+8, 3+6+9]]) ,而最后两行被省略;

现在最优雅、最有效的解决方案是什么?网上查了很多,没有找到类似的问题

最佳答案

这是一种方法 -

def sum_in_blocks(a, c):
# Get extent of each col for summing
l = c*(len(a)//c)

# Reshape to 3D considering first l rows, and "cutting" after each c rows
# Then sum along second axis
return a[:l].reshape(-1,c,a.shape[1]).sum(1)

有关第二步的更多信息 - General idea for nd to nd transformation .

示例运行 -

In [79]: a
Out[79]:
array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12],
[13, 14, 15]])

In [80]: sum_in_blocks(a, c=1)
Out[80]:
array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12],
[13, 14, 15]])

In [81]: sum_in_blocks(a, c=2)
Out[81]:
array([[ 5, 7, 9],
[17, 19, 21]])

In [82]: sum_in_blocks(a, c=3)
Out[82]: array([[12, 15, 18]])
<小时/>

给定示例的说明

In [84]: a
Out[84]:
array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12],
[13, 14, 15]])

In [85]: c = 2

In [87]: l = c*(len(a)//c) # = 4; Get extent of each col for summing

In [89]: a[:l] # hence not relevant rows are skipped
Out[89]:
array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12]])

# Reshape to 3D "cutting" after every c=2 rows
In [90]: a[:l].reshape(-1,c,a.shape[1])
Out[90]:
array([[[ 1, 2, 3],
[ 4, 5, 6]],

[[ 7, 8, 9],
[10, 11, 12]]])

# Sum along axis=1 for final o/p
In [91]: a[:l].reshape(-1,c,a.shape[1]).sum(axis=1)
Out[91]:
array([[ 5, 7, 9],
[17, 19, 21]])

关于python - 如何计算Python中numpy数组中n个元素的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59019698/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com