这是一个SKU亲和性问题。我有一个这样的数据帧。每个ctn_id都有多个sku_codes。
dfr = pd.DataFrame(columns=['ctn_id','sku_code'])
dfr['ctn_id'] = np.random.randint(low=1,high=21,size=200)
dfr['sku_code'] = np.random.choice(['a','b','c','d'],size=200)
dfr.drop_duplicates(['ctn_id','sku_code'], inplace=True)
我想填写以下数据帧。
dfx = pd.DataFrame(columns=['sku_code','a','b','c','d'])
dfx['sku_code'] = ['a','b','c','d']
dfx = dfx.fillna(0)
dfx.set_index('sku_code',inplace=True)
使用下面的逻辑
for idx in dfr['ctn_id'].unique():
x = list(dfr[dfr['ctn_id'] == idx]['sku_code'].unique())
for skui in dfx.index:
if skui in x:
for skuj in x:
dfx.loc[skui, skuj] = dfx.loc[skui, skuj] + 1
我有250万的ctn_ids和400亿的sk_codes,总共有十亿次赋值操作。有没有更好的方法来使用pandas或任何其他包来做到这一点?
发布于 2019-04-25 05:48:49
好吧,我会试一试。
我不确定这是否足够快,但我想说它已经比你的for循环快得多了。
它使用了一种老套的方式来执行“矢量化”的集合差异。
s = df.groupby(['sku_code']).ctn_id.agg(set)
pd.DataFrame(map(lambda s: list(map(len,s)), np.array(s) & np.array(s).reshape([-1,1])))
0 1 2 3
0 18 17 18 16
1 17 19 19 17
2 18 19 20 17
3 16 17 17 17
使用您提供的示例,性能提高了大约100倍。
# your method
79.4 ms ± 3.3 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# my try
668 µs ± 30.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
https://stackoverflow.com/questions/55838406
复制相似问题