英文:
Python: For a 2D array, sum the 2nd col of the non-unique elements in first col?
问题
请问您能帮我解决这个问题吗?
我有一个已排序的 2D numpy 数组,第一列中有一些重复的元素,我想创建一个新的已排序数组,其中第二列对重复元素求和。
例如,我有一个 2x4 数组:
y = np.array(([14.0, 100], [15.0, 130], [15.0, -90], [16.0, 60]))
我想要以下 2x3 数组:
z = np.array(([14.0, 100], [15.0, 40], [16.0, 60]))
我正在尝试使用 reduce/map/lambda,但还没有成功。
英文:
Hi Please could you help me with this problem.
I have a sorted 2D numpy array with some repeated elements in the first col, I would like to create a new sorted array where the 2nd column has summed the repeated elements.
E.g. I have a 2 by 4 array:
y = np.array(([14.0, 100], [15.0, 130], [15.0, -90], [16.0, 60]))
I want the following 2 by 3 array:
z = np.array(([14.0, 100], [15.0, 40], [16.0, 60]))
I'm looking at reduce/map/lambda but haven't got it to work yet.
答案1
得分: 1
以下是已翻译的内容:
sums=[np.sum(y[:,1],where=y[:,0]==a) for a in np.unique(y[:,0])]
counts=np.stack([np.unique(y[:,0]),sums],axis=1)
这给出了以下结果:
[[ 14. 100.]
[ 15. 40.]
[ 16. 60.]]
英文:
sums=[np.sum(y[:,1],where=y[:,0]==a) for a in np.unique(y[:,0])]
counts=np.stack([np.unique(y[:,0]),sums],axis=1)
This gives the following result:
[[ 14. 100.][ 15. 40.][ 16. 60.]]
答案2
得分: 0
使用 np.unique
+ np.split
:
u, idx = np.unique(Y[:, 0], return_index=True)
Z = np.column_stack([u, [a.sum() for a in np.split(Y[:,1], idx)[1:]])
结果为:
array([[ 14., 100.],
[ 15., 40.],
[ 16., 60.]])
英文:
With np.unique
+ np.split
:
u, idx = np.unique(Y[:, 0], return_index=True)
Z = np.column_stack([u, [a.sum() for a in np.split(Y[:,1], idx)[1:]]])
array([[ 14., 100.],
[ 15., 40.],
[ 16., 60.]])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论