我正在尝试将多个函数应用于panda中的不同列。我的数据帧由超过1000万行和超过10万个组组成。我正在尝试类似的操作(下面的示例(,但这需要很长时间。我试过用dask,但也没用。
关于如何改进下面的示例,有什么建议吗?
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.rand(4,4), columns=list('abcd'))
df['group'] = [0, 0, 1, 1]
def f(x):
d = {}
d['a_sum'] = x['a'].sum()
d['a_max'] = x['a'].max()
d['b_mean'] = x['b'].mean()
d['c_d_prodsum'] = (x['c'] * x['d']).sum()
return pd.Series(d, index=['a_sum', 'a_max', 'b_mean', 'c_d_prodsum'])
df.groupby('group').apply(f)
使用命名聚合来避免MultiIndex in columns
和c_d_prodsum
是辅助列的多个列:
np.random.seed(2020)
df = pd.DataFrame(np.random.rand(4,4), columns=list('abcd'))
df['group'] = [0, 0, 1, 1]
df1 = (df.assign(tmp=df['c'] * df['d'])
.groupby('group').agg(a_sum =('a', 'sum'),
a_max =('a', 'max'),
b_mean = ('b', 'mean'),
c_d_prodsum = ('tmp', 'sum')))
print (df1)
a_sum a_max b_mean c_d_prodsum
group
0 1.323196 0.986277 0.545173 0.233486
1 1.598484 0.862159 0.256181 0.334105
用.agg
聚合它们有帮助吗?
import pandas as pd
df = pd.DataFrame(np.random.rand(4,4), columns=list('abcd'))
df['group'] = [0, 0, 1, 1]
df['c_d_prod'] = df['c'] * df['d']
df = df.groupby('group').agg({'a' : ['sum', 'max'], 'b' : ['mean'], 'c_d_prod': ['sum'] })
print(df)
输出:
a b c_d_prod
sum max mean sum
group
0 1.693675 0.966228 0.500866 0.155463
1 0.950398 0.786002 0.355562 0.557794
如果您愿意,您可以重命名列:
df.columns = ['a_sum', 'a_max', 'b_mean', 'c_d_prodsum']
print(df)
输出:
a_sum a_max b_mean c_d_prodsum
group
0 0.899459 0.736511 0.233027 1.287123
1 0.913862 0.654808 0.730330 0.177089