【发布时间】:2018-10-13 10:17:35
【问题描述】:
方法一(清晰但很慢)
product_ids = df1.product_id.unique()
store_ids= df1.store_id.unique()
with tqdm(total=product_ids.shape[0]*store_ids.shape[0]) as t:
for product_id in product_ids:
p1 = df1.loc[(df1.product_id==product_id)]
p2 = df2.loc[(df2.product_id==product_id)]
for store_id in store_ids:
df11 = p1.loc[(p1.store_id==store_id)]
df22 = p2.loc[(p2.store_id==store_id)]
train_predict(df11, df22)
t.update()
方法2(快但我不喜欢)
df1 = df1.reset_index()
df2 = df2.reset_index().set_index(['store_id', 'product_id'])
def _reduce(df_orderitems):
MIN_ORDERITEMS_COUNT = 30
store_id = df_orderitems.store_id.iloc[0]
product_id = df_orderitems.product_id.iloc[0]
try:
## !!!! here refer to global df2, I don't like !!!!!
df_stockquantitylog = df2.loc[(store_id, product_id)]
## !!!! here refer to global df2, I don't like !!!!!
except KeyError:
logger.info('## df_orderitems shape:%s , cannot find (%s, %s)' % (df_orderitems.shape, store_id, product_id) )
return
train_predict(df_orderitems, df_stockquantitylog)
tqdm.pandas()
df1.groupby(['store_id', 'product_id']).progress_apply(_reduce)
我需要 tqdm 来显示进度条,但是 Method1 很慢(我认为是因为打印效率低下)。方法2有tqdm的pandas补丁,我认为另一个关键点是groupby.apply。但我不知道如何让方法 1 和方法 2 一样快。
注意:
df1.shape[0] != df2.shape[0] ,无法合并。
它们是从数据库中转储的。例如,df1 中可能有 10 行 store_id A 和 product_id B 相同,df2 中可能有 100 行 store_id A 和 product_id B 相同。在正确处理之前不能合并它们:
需要:
- 首先按 store_id 和 product_id 选择(在每个 df1 和 df2 中)
- 没有选择就无法加入。我必须对
df1[(df1.store_id==A)&(df1.product_id==B)])和df2[(df2.store_id==A)&(df2.product_id==B)])应用不同的聚合,以便为它们提供相同的DatatimeIndex 进行合并,因为某些元数据列需要按日期聚合。您不能在没有选择的情况下执行此操作,因为store_id和product_id的不同组合具有重复的日期。 - 那么这两个结果是mergable(joinable)
- 训练模型
【问题讨论】:
标签: python pandas progress-bar pandas-groupby tqdm