Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在聚合二进制列的大型数据集上优化pandas groupby()_Python_Pandas_Numpy_Group By_Pandas Groupby - Fatal编程技术网

Python 在聚合二进制列的大型数据集上优化pandas groupby()

Python 在聚合二进制列的大型数据集上优化pandas groupby(),python,pandas,numpy,group-by,pandas-groupby,Python,Pandas,Numpy,Group By,Pandas Groupby,我有一个数据帧,格式如下: template is_a is_b is_c is_d is_e 0 cv_template 0 1 0 0 0 1 topic_template 1 0 0 0 0 2 model_template 1 0 0 0 0 3 model_template 0 1 0 0 0

我有一个数据帧,格式如下:

   template          is_a is_b is_c is_d is_e
0  cv_template        0    1     0    0    0
1  topic_template     1    0     0    0    0
2  model_template     1    0     0    0    0
3  model_template     0    1     0    0    0               
我想按
模板
分组,并聚合
is
列,这些列是每个
模板
的二进制值

i、 e.在上述示例中,输出为:

   template          is_a is_b is_c is_d is_e
0  cv_template        0    1     0    0    0
1  topic_template     1    0     0    0    0
2  model_template     1    1     0    0    0         
我目前的解决方案是这样做:

df.groupby('template',as_index=False)['is_a','is_b','is_c','is_d'].max()


然而,在处理大型数据集时,分组速度较慢。我想知道是否有更好的方法可以加快速度。

我不能肯定这会快得多。但是,我把这个和Numba放在一起

import pandas as pd
import numpy as np
from numba import njit

@njit
def max_at(i, a, shape):
    out = np.zeros(shape, np.int64)
    for j in range(len(a)):
        row = a[j]
        pos = i[j]
        cur = out[pos]
        out[pos, :] = np.maximum(cur, row)
    return out

i, t = df['template'].factorize()
cols = ['is_a', 'is_b', 'is_c', 'is_d', 'is_e']
is_ = np.column_stack([df[c].to_numpy() for c in cols])

result = max_at(i, is_, (len(t), len(cols)))

pd.DataFrame(result, t, cols).reset_index()

            index  is_a  is_b  is_c  is_d  is_e
0     cv_template     0     1     0     0     0
1  topic_template     1     0     0     0     0
2  model_template     1     1     0     0     0

你的解决方案是合理的。您的数据集有多大?它能跑多久?@QuangHoang,它很大~50米行。任何一点点的优化都很方便。