Python 合并在熊猫身上的作用

Python 合并在熊猫身上的作用,python,pandas,merge,Python,Pandas,Merge,我贴了一个问题并得到了答案 你能解释一下joinfinal\u df=pd.merge(df,temp\u df.reset\u index(),how=“left”).fillna(0)是如何工作的吗?我得到了正确的结果,但我不明白联接是如何发生的。df和temp_df之间没有公共列 工作代码如下: d = {'emp': ['a', 'a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'c

我贴了一个问题并得到了答案

你能解释一下join
final\u df=pd.merge(df,temp\u df.reset\u index(),how=“left”).fillna(0)
是如何工作的吗?我得到了正确的结果,但我不明白联接是如何发生的。df和temp_df之间没有公共列

工作代码如下:

    d = {'emp': ['a',   'a',    'a',    'a',    'b',    'b',    'b',    'c',    'c',    'c',    'c' ], 
     'date': ['1',  '1',    '1',    '1',    '2',    '2',    '2',    '3',    '3',    '3',    '3' ], 
     'usd':[1,  2,  3,  4,  5,  6,  7,  8,  9,  10,     11 ], 
     'expense type':['Car Mileage',     'Car Rental',   'Car Rental - Gas',     'food',     'Car Rental',   'Car Rental - Gas',     'food',     'Car Mileage',  'Car Rental',   'food',     'wine' ],
     'zflag':['1',  '1', '1',   ' ',' ',' ',' ','2','2',' ',' ' ]
     }

    df = pd.DataFrame(data=d)



        df
    Out[253]: 
       date emp      expense type  usd zflag
    0     1   a       Car Mileage    1     1
    1     1   a        Car Rental    2     1
    2     1   a  Car Rental - Gas    3     1
    3     1   a              food    4      
    4     2   b        Car Rental    5      
    5     2   b  Car Rental - Gas    6      
    6     2   b              food    7      
    7     3   c       Car Mileage    8     2
    8     3   c        Car Rental    9     2
    9     3   c              food   10      
    10    3   c              wine   11   


temp_df = df.groupby(["emp", "date"], axis=0)["expense type"].apply(lambda x: 1 if "Car Mileage" in x.values and any([k in x.values for k in ["Car Rental", "Car Rental - Gas"]]) else 0).rename("zzflag")
temp_df = temp_df.loc[temp_df!=0,:].cumsum()
final_df = pd.merge(df, temp_df.reset_index(), how="left").fillna(0)
更新1:
temp_df
没有索引,它是一个系列。因此,我不确定如何在注释中建议的索引上发生连接

temp_df
Out[335]: 
emp  date
a    1       1
c    3       2
Name: zzflag, dtype: int64

pd.merge
不带
on
index
参数在公共列名上连接:

查看“on”参数:

关于:标签或列表 要加入的字段名。必须在两个数据帧中都找到。如果打开,则为 无,不在索引上合并,然后在 默认情况下,列将被删除

输出:

True

@Ni_Tempe发生的事情是,带有out参数的pd.merge正在合并公共列名,如“emp”和“date”
True