[英]Add items in numpy arrays where each item has an associated “type”
I'm wondering if it's possible to add numpy
arrays together item-wise, where each item has a "type" associated with it.我想知道是否可以逐项添加
numpy
arrays ,其中每个项目都有一个与之关联的“类型”。
For example, say I have the following 2 arrays:例如,假设我有以下 2 个 arrays:
array1 = [[2 'x'] [3 'y'] [4 'z']]
array2 = [[10 'x'] [6 'z']]
And I would like to produce this array:我想生成这个数组:
array3 = [[12 'x'] [3 'y'] [10 'z']]
Is there a straightforward way to do this using numpy
?有没有使用
numpy
的简单方法来做到这一点? Thanks!谢谢!
You can either use numpy directly or make advantage of pandas built-in groupby method.您可以直接使用 numpy 或利用 pandas 内置 groupby 方法。
Numpy Implementation Numpy 实现
import numpy as np
a1 = np.array([[2, 'x'], [3, 'y'], [4 ,'z']])
a2 = np.array([[10, 'x'] ,[6 ,'z']])
# Stack the two arrays together
a = np.vstack([a1,a2])
# Define "groups"
grp = np.unique(a[:,1])
# Groupby each group in grp and sum the other column
np.array([[a[a[:,1]==g][:,0].astype(float).sum(), g] for g in grp])
array([['12.0', 'x'],
['3.0', 'y'],
['10.0', 'z']], dtype='<U32')
Pandas Implementation Pandas 实施
import pandas as pd
# Convert a into a pandas DataFrame
df = pd.DataFrame(a, columns=list('ab'))
# Cast first column type
df['a'] = df['a'].astype(int)
# Use groupby sum
df.groupby('b').sum().reset_index()[['a','b']].to_numpy()
array([[12, 'x'],
[3, 'y'],
[10, 'z']], dtype=object)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.