gpt4 book ai didi

python - 基于索引的二维数组中的 Numpy 组合值

转载 作者:太空宇宙 更新时间:2023-11-04 02:26:39 26 4
gpt4 key购买 nike

我有一个基于这种格式的 numpy 数组 [[x,y],[x,y]...]我想结合这个 y x 所在的值都是一样的

示例 array = [[0,0],[1,1],[2,4],[4,6],[2,2],[3,7],[1,9],[4,16],[5,1],[5,2],[0,0]]

我希望它变成 newArray = [[0,0],[1,10],[2,6],[3,7],[4,22],[5,3]] - 无需订购

好像现在我想不出一种简单有效地做到这一点的方法,它可能有助于在我的实际数组中添加使用时间戳作为我的 x值如 Timestamp('2018-05-05 00:00:00')大小为 183083,还算不错。

任何帮助适用!

最佳答案

numpy 解决方案可用,如果性能是一个问题:Sum array by number in numpy

下面是一个使用 collections.defaultdict 的基于字典的方法。这是通过迭代数组中的每一行并按键对值求和来实现的。

import numpy as np
from collections import defaultdict

A = np.array([[0,0],[1,1],[2,4],[4,6],[2,2],[3,7],[1,9],[4,16],[5,1],[5,2],[0,0]])

d = defaultdict(int)
for i, j in A:
d[i] += j

res = np.array(sorted(d.items()))

print(res)

array([[ 0, 0],
[ 1, 10],
[ 2, 6],
[ 3, 7],
[ 4, 22],
[ 5, 3]])

关于python - 基于索引的二维数组中的 Numpy 组合值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50212316/

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