Replace column values based on another dataframe python pandas - better way?

后端 未结 4 690
眼角桃花
眼角桃花 2020-12-01 02:42

Note:for simplicity\'s sake, i\'m using a toy example, because copy/pasting dataframes is difficult in stack overflow (please let me know if there\'s an easy way to do this)

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-01 03:31

    In [27]: This is the correct one.

    df.loc[df.Name.isin(df1.Name), ['Nonprofit', 'Education']] = df1[['Nonprofit', 'Education']].values
    
    df
    Out[27]:
    
    Name  Nonprofit  Business  Education
    
    0    X          1         1          0
    1    Y          1         1          1
    2    Z          1         0          1
    3    Y          1         1          1
    

    [4 rows x 4 columns]

    The above will work only when all rows in df1 exists in df . In other words df should be super set of df1

    Incase if you have some non matching rows to df in df1,you should follow below

    In other words df is not superset of df1 :

    df.loc[df.Name.isin(df1.Name), ['Nonprofit', 'Education']] = 
    df1.loc[df1.Name.isin(df.Name),['Nonprofit', 'Education']].values
    

提交回复
热议问题