python - 如何加快大数据集中的两个嵌套 for 循环
问题描述
我正在处理一个 600.000 x 128 的数据集,按以下形式排列,并带有层次索引(见左图):
Var1 Var2 ... Var1_mean Var2_mean ...
ID Date ID Date
1 2017-12 1 0.1 1 2017-12 2 0.3
1 2018-01 2 0.3 1 2018-01 2 0.3
1 2018-02 3 0.5 --> 1 2018-02 2 0.3
2 2018-01 2 0.2 2 2018-01 3 0.15
2 2018-02 4 0.1 2 2018-02 3 0.15
现在对于所有 55.000 个客户(= 唯一 ID),我想用每个客户的平均值替换所选变量中每个客户的值,存储在新变量中(变量名称 + '_mean',见右图)。
我写了一个函数来做到这一点,但它需要 4 个多小时,即使在尝试并行化任务之后也是如此。我试过了:
identifiers = set(df_raw_sort.index.get_level_values(0)) # unique IDs
def avg_per_customer(column):
df_raw_sort.loc[:, column + '_mean'] = 0 # Create new col
for unique in identifiers:
meanvalue = np.mean(df_raw_sort[column].loc[(unique)])
df_raw_sort.loc[(unique), column + '_mean'] = meanvalue
Parallel(n_jobs=2, verbose=10)(delayed(avg_per_customer)(col) for col in transform)
# transforms selected columns (= transform)
我能做些什么来加快这件事?
提前非常感谢。
解决方案
你能试试这个
df_raw_sort[variable_name_mean] = df_raw_sort[variable_name].groupby(df_raw_sort['ID']).transform('mean')
推荐阅读
- dynamics-crm - 如何使用 FetchXML 计算总值
- php - 解析 MySQLi 查询语句以获取 PDO 迁移的参数
- c# - 如何修复“无法将 BaseExpandableListAdapter 类型隐式转换为 Android.Widget.IListAdapter”
- typescript - 如何缩小派生类的只读属性的类型?
- symfony - 如何在“/api”文档 api-platform 上添加我的自定义错误
- javascript - 需要延迟加载 iframe
- javascript - 如何在 d3.js 中绘制指南针形状并为每个三角形着色不同?
- javascript - 使用 addEventListener 运行时“不是函数”
- clojure - 如何在 Clojure 中将字符串附加到向量
- c# - 是否可以将字符串中的字符与字符集进行比较?