Python Numpy - 多个组的聚合 numpy 数组



我有一个这样的数组:

([(1, 1, 10),
(1, 1, 20),
(1, 2, 10),
(2, 1, 30),
(2, 1, 40),
(2, 2, 20)],
dtype=[('id', '<i8'), ('group', '<i8'), ('age', '<i8')])

我想聚合这个数组,将 bu 'id' 和 'age' 分组,得到年龄的平均值。

我想得到这个结果:

([(1, 1, 15),
(1, 2, 10),
(2, 1, 35),
(2, 2, 20)],
dtype=[('id', '<i8'), ('group', '<i8'), ('age', '<i8')])

我已经看到了熊猫的简单方法,但我真的在寻找一种用 numpy 的方法。我试过了:

unique, uniqueInd, uniqueCount = np.unique(old_array['id'], return_inverse=True, return_counts=True)
means = np.bincount(uniqueInd, old_array['age'])/uniqueCount
new_array = np.dstack([unique, means])

但我无法让它按多列展开和分组。

非常感谢:)!

您可以将带权重的箱计数除以图谱计数,而无需使用权重来获取平均值。

import numpy as np
a = np.array([(1, 1, 10),
(1, 1, 20),
(1, 2, 10),
(2, 1, 30),
(2, 1, 40),
(2, 2, 20)],
dtype=[('id', '<i8'), ('group', '<i8'), ('age', '<i8')])

ans, indices = np.unique(a[['id', 'group']], return_inverse=True)
means = np.bincount(indices, a['age']) / np.bincount(indices)
answer = np.empty(means.size, dtype=a.dtype)
answer['id'] = ans['id']
answer['group'] = ans['group']
answer['age'] = means
print(answer)
# [(1, 1, 15) (1, 2, 10) (2, 1, 35) (2, 2, 20)]

最新更新