在pandas
中执行分组和聚合既简单又快速。但是,由于lambda函数的存在,执行简单的groupby apply函数要慢得多,因为pandas
已经在C中构建了这些函数,而没有聚合
# Form data
>>> import numpy as np
>>> import pandas as pd
>>> df = pd.DataFrame(np.random.random((100,3)),columns=['a','b','c'])
>>> df['g'] = np.random.randint(0,3,100)
>>> df.head()
a b c g
0 0.901610 0.643869 0.094082 1
1 0.536437 0.836622 0.763244 1
2 0.647989 0.150460 0.476552 0
3 0.206455 0.319881 0.690032 2
4 0.153557 0.765174 0.377879 1
# groupby and apply and aggregate
>>> df.groupby('g')['a'].sum()
g
0 17.177280
1 15.395264
2 17.668056
Name: a, dtype: float64
# groupby and apply without aggregation
>>> df.groupby('g')['a'].transform(lambda x: x.sum())
0 15.395264
1 15.395264
2 17.177280
3 17.668056
4 15.395264
95 15.395264
96 17.668056
97 15.395264
98 17.668056
99 17.177280
Name: a, Length: 100, dtype: float64
因此,我拥有lambda函数所需的功能,但速度很差
>>> %timeit df.groupby('g')['a'].sum()
1.11 ms ± 143 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
>>> %timeit df.groupby('g')['a'].transform(lambda x:x.sum())
4.01 ms ± 699 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
这在较大的数据集中成为一个问题。我假设有一个更快、更高效的方法来获得这个功能
也许你在找
确实比使用apply的版本更快:
输出:
相关问题 更多 >
编程相关推荐