Pandas 用于pd.merge的For循环

Pandas 用于pd.merge的For循环,pandas,dataframe,Pandas,Dataframe,我试图使用for循环,根据列上的城市和行上的发票号合并总销售额,最终结果只发生在最后一个城市 import pandas as pd Super=pd.read_excel(r"C:\supermarket_sales.xlsx") def Summary(city): Location=Super[Super["City"]==city] PDT=Location.groupby(["Product line",&q

我试图使用for循环,根据列上的城市和行上的发票号合并总销售额,最终结果只发生在最后一个城市

import pandas as pd
Super=pd.read_excel(r"C:\supermarket_sales.xlsx")

def Summary(city):
    Location=Super[Super["City"]==city]
    PDT=Location.groupby(["Product line","Invoice ID"])["Total"].sum()
    PDTT=PDT.reset_index()
    PDTT.rename(columns={"Total": city+"Total"},inplace=True)
    return PDTT

for city in Super['City'].unique():
    PDT = Summary(city)

Invoice=Super["Invoice ID"]

for city in Super['City'].unique():
    df=Summary(city)
    L3V=pd.merge(Invoice,df[["Invoice ID",city+"Total"]],on ="Invoice ID",how="left")
按代码输出:

预期产量


最终结果仅包括最后一个城市,因为在
for
循环中,在每次迭代中,您都从
pd.merge
重新创建新的L3V数据帧,并且先前城市的信息丢失。所以在循环的最后,你只剩下最后一个城市的信息

您需要保存每个城市的合并数据,并将其他城市合并到其中。最后一次循环是否如下所示:

Invoice = Super["Invoice ID"]
L3V = Invoice.copy()

for city in Super['City'].unique():
    df = Summary(city)
    L3V = pd.merge(L3V, df[["Invoice ID",city+"Total"]], on ="Invoice ID", how="left")