python - Python numpy groupby 多列
问题描述
有没有办法通过 numpy 中的多列聚合来创建一个组?我试图用这个模块做到这一点:https ://github.com/ml31415/numpy-groupies 目标是获得比熊猫更快的 groupby。例如:
group_idx = np.array([
np.array([4, 3, 3, 4, 4, 1, 1, 1, 7, 8, 7, 4, 3, 3, 1, 1]),
np.array([4, 3, 2, 4, 7, 1, 4, 1, 7, 8, 7, 2, 3, 1, 14 1]),
np.array([1, 2, 3, 4, 5, 1, 1, 2, 3, 4, 5, 4, 2, 3, 1, 1])
]
a = np.array([1, 2, 1, 2, 1, 2, 1, 2, 3, 4, 5, 4, 2, 3, 1, 1])
result = aggregate(group_idx, a, func='sum')
它应该像熊猫 df.groupby(['column1','column2','column3']).sum().reset_index()
解决方案
鉴于它group_idx
具有正值,我们可以使用基于降维的方法。我们假设前三列作为分组列,最后(第四)一列作为要求和的数据列。
方法#1
我们将坚持使用 NumPy 工具并引入pandas.factorize
混合。
group_idx = df.iloc[:,:3].values
a = df.iloc[:,-1].values
s = group_idx.max(0)+1
lidx = np.ravel_multi_index(group_idx.T,s)
sidx, unq_lidx = pd.factorize(lidx)
pp = np.empty(len(unq_lidx), dtype=int)
pp[sidx] = np.arange(len(sidx))
k1 = group_idx[pp]
a_sums = np.bincount(sidx,a)
out = np.hstack((k1, a_sums.astype(int)[:,None]))
方法#2
引入 numba 和排序 -
import numba as nb
@nb.njit
def step_sum(a_s, step_mask, out, group_idx_s):
N = len(a_s)
count_iter = 0
for j in nb.prange(3):
out[count_iter,j] = group_idx_s[0,j]
out[count_iter,3] = a_s[0]
for i in nb.prange(1,N):
if step_mask[i-1]:
out[count_iter,3] += a_s[i]
else:
count_iter += 1
for j in nb.prange(3):
out[count_iter,j] = group_idx_s[i,j]
out[count_iter,3] = a_s[i]
return out
group_idx = df.iloc[:,:3].values
a = df.iloc[:,-1].values
s = group_idx.max(0)+1
lidx = np.ravel_multi_index(group_idx.T,s)
sidx = lidx.argsort()
lsidx = lidx[sidx]
group_idx_s = group_idx[sidx]
a_s = a[sidx]
step_mask = lsidx[:-1] == lsidx[1:]
N = len(lsidx)-step_mask.sum()
out = np.zeros((N, 4), dtype=int)
out = step_sum(a_s, step_mask, out, group_idx_s)
比较检查
为了进行比较检查,我们可以使用类似的东西:
# get pandas o/p and lexsort
p = df.groupby(['agg_a','agg_b','agg_c'])['to_sum'].sum().reset_index().values
p = p[np.lexsort(p[:,:3].T)]
# Output from our approaches here, say `out`. Let's lexsort
out = out[np.lexsort(out[:,:3].T)]
print(np.allclose(out, p))
推荐阅读
- url - url 作为参数?在 ASP.NET 核心中
- java - 无法验证选中的复选框,Selenium Webdriver Java
- jenkins - Jenkins+RTC:是否有任何 jenkins 插件具有在不加载 RTC 服务器的情况下检查更改的功能
- python - 根据另一个文件中的字符串重命名文件夹中的文件-使用Python
- javascript - 有没有办法检查一个 npm 包是否需要发布,然后才发布?
- ngxs - Ngxs - 如何在应用程序加载时预填充状态
- java - 如何使扫描仪返回分隔符作为标记
- android - 如何在尝试使用 GeckoView 时修复此错误“错误:找不到方法 compileOptions()”?
- python - 无法访问属于同一类的其他函数的函数中的变量
- java - 如何调用 H2 LINK_SCHEMA?