加速向Datafram分配值的循环

2024-09-30 02:29:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个功能运行得有点慢,我不喜欢,似乎不能使它更快。我有57种产品和402家商店。下面的函数创建dataframe,其中products作为索引,并作为列存储。目标是获取按产品销售的最大数量,存储并将其分配给“unconstraintload_df”数据帧。它似乎在做这项工作,但它需要大量的时间才能完成。请问,有没有人有加快速度的想法

def getmaxsaleperproduct_and_store(product,store):
    return training_DS[(training_DS["Prod Code"]==product)&(training_DS["Store"]==store)]["Sold Qty"].max()

def unconstraintsales():
    global unconstraintload_df

    ProdCodeList = training_DS["Prod Code"].unique()
    StoreNumberList = training_DS["Store"].unique()

    unconstraintload_df = pd.DataFrame(index=StoreNumberList,columns=ProdCodeList)

    for store in StoreNumberList:
        for prod in ProdCodeList:
            unconstraintload_df.loc[unconstraintload_df.index==store,prod] = getmaxsaleperproduct_and_store(prod,store)


Tags: andstoredfdeftrainingdscodeprod
2条回答

考虑^{},避免嵌套循环。记住,Pandas中的聚合很少需要循环,这与使用列表、元组或字典的通用Python不同:

unconstraintload_df = pd.pivot_table(training_DS, index="Prod Code", columns="Store", 
                                     values="Sold Qty", aggfunc="max")

此外,报告之外的宽数据集往往不如长格式有用。考虑使用{{CD2}}的长格式聚合,避免400个+列管理:

long_agg_df = training_DS.groupby(["Prod Code", "Store"])["Sold Qty"].max()

尝试:

unconstraintload_df = training_DS[["Store", "Prod Code", "Sold Qty"]].groupby(["Store", "Prod Code"]).max().reset_index()

相关问题 更多 >

    热门问题