如何高效实现基于DataFrame B的axis=1方向qcut分箱对A行求和?
基于DataFrame B的行向qcut分箱对DataFrame A进行行求和的性能优化
需求说明
- 沿
axis=1方向,基于DataFrame B的qcut分箱结果对DataFrame A的值进行行求和 - A与B的索引、列完全一致
- 分箱参数
q可自定义 - B中允许存在NaN值
示例代码
import pandas as pd import numpy as np A = pd.DataFrame( {'a': [4, 8, -2, -6, 7, -3, 4], 'b': [-8, 8, 6, 6, 5, -3, -2], 'e': [1, 34, -13, 5, 0, 8, -76], 'c': [1, 2, 6, 3, 8, -4, -20], 'd': [4, 0, 3, -4, 8, 4, 2]}) B = pd.DataFrame( {'a': [34, 78, -2, -96, np.nan, -34, 44], 'b': [-82, 28, 96, 46, np.nan, -3, -20], 'e': [12, 324, -123, 56, np.nan, 8, -876], 'c': [np.nan, 28, 96, np.nan, 8, -34, -20], 'd': [42, -40, 23, -40, -50, 10, 97]}) q = [0, 0.33, 0.66, 1]
预期输出
0 1 2 0 -8.0 1.0 8.0 1 10.0 0.0 42.0 2 -15.0 3.0 12.0 3 -6.0 -4.0 11.0 4 8.0 0.0 8.0 5 -7.0 -3.0 12.0 6 -98.0 0.0 6.0
现有实现方法
bins = B.apply(lambda x: pd.qcut(x, q, labels=False), axis=1) out = pd.concat( [A.mask(bins!=x, np.nan).sum(axis=1) for x in range(len(q)-1)], axis=1)
性能问题
现有方法速度较慢,主要瓶颈在qcut的行向应用环节。针对3000行×500列的数据,qcut操作耗时约2.7秒,求和操作仅耗时约130毫秒。
问题
是否存在显著更快的实现方式?
内容的提问来源于stack exchange,提问作者handlist
相关产品推荐
相关产品推荐

