理想情况下,我希望重用GroupBy对象来提高密集型操作的性能 .

我有一个包含多个分类列和值列的DataFrame,我希望能够对各种列组合进行groupby操作,请考虑以下事项:

import numpy as np
import pandas as pd

# Build some data to work with:
sim_elements = 1e6
sims = 1e5
class_dict = {0:'A', 1:'B', 2:'C', 3:'D', 4:'E'}

d = {'Year': np.random.randint(1, sims+1, size=sim_elements),
     'Month': np.random.randint(1, 12+1, size=sim_elements),
     'Day': np.random.randint(1, 29, size=sim_elements),
     'Sid': np.random.randint(1e6, size=sim_elements),
     'Class': [class_dict[i] for i in 
               np.random.randint(len(class_dict.keys()), size=sim_elements)],
     'Value': np.random.uniform(size=sim_elements) * 1e6}
df = pd.DataFrame(d)

# Execute a groupby operation across all columns and sum over the Value column.
gb = df.groupby(('Year', 'Month', 'Day', 'Class', 'Sid')).agg({'Value': np.sum})
gb

如果我将操作应用于Value列,那么我想重新计算groupby操作:

df.Value *= np.random.uniform(0,2, size=sim_elements)
gbn = df.groupby(('Year', 'Month', 'Day', 'Region', 'Sid')).agg({'Value': np.sum})

在跨越sim_elements的大值时执行此操作很慢,并且每次运行我执行此操作数百次 . 1e6需要大约4秒,1e7需要大约50秒,我需要有效支持至少2e7个元素 .

我认为计算的groupby MultiIndex应该可以重用来重新计算新的agg函数(np.sum就是一个例子),但我无法弄清楚如何应用它 . 如何最有效地在具有相同形状和列结构的数据帧上多次重用groupby方法?