首页 > 解决方案 > 将所有循环结果保存到 Python Pandas 中的数据框有问题吗?

问题描述

我有一个像下面这样的循环,这样做我需要计算 store = 1 和 store = 85 的预测,但没关系......真正的问题是,为什么在结果数据框中:“df_all_2”我只有结果存储 1,所以我的循环运行不好,因为我需要存储 85 和 1 的结果,但我没有看到此循环中的错误,你能帮帮我吗?

sample_df = data.query('Store in [85, 1]')
Store_list = sample_df["Store"].unique().tolist()

df_result = pd.DataFrame(columns=["Date", "Store", "Sales", "Sales_Prediction"])
df_result.set_index("Date", inplace=True)

for store in Store_list:
    sample_df = data_XGB[data_XGB["Store"]==store]

    ......
    
    test_set['Sales_Prediction'] = reg.predict(X_test_XGB)
    train_set['Sales_Prediction'] = reg.predict(X_train_XGB)
    
    df_all = pd.concat([test_set, train_set], sort=True)
    df_all = df_all[["Store", "Sales", "Sales_Prediction"]]
    df_all.reset_index(inplace=True)
    df_all["Date"] = df_all["Date"].astype("datetime64")
    df_all.sort_values(by="Date", inplace=True)
    df_all.set_index("Date", inplace=True)
    
df_all_2 = pd.concat([df_result, df_all], sort=False)

在此处输入图像描述

例如,我尝试写:df_result = df_result.combine_first(df_all)而不是 last 像 df_all_2 但是当我使用带有缩进的代码时,我只有 85 的结果并且没有缩进,我只有 1 的结果,但我需要同时拥有 1 和 85。

我假设我覆盖了我的循环,但我不知道如何?

标签: pythonpandasdataframeloops

解决方案


尝试使用应用

def sales_pred(store):
    if store == 1 or store ==85:
       # do your sales prediction logic here

    return #prediction

df_result.loc[:, 'sales_prediction'] = df1.apply(lambda x: matches_lookup(x['store'], axis=1)

推荐阅读