如何比较不同数据框熊猫中的两列并用其他列替换值

时间:2020-09-15 14:46:50

标签: python pandas

我想比较df_1(数据帧)中的'Team_1'和df_2(数据帧)中的'Team_Id',无论何时找到匹配项,我都想用df_2中Team_Name中的相应值替换df_1中Team_1的值。所以我可以继续使用df_1

例如:如果df_1中的Team_1 = 1和df_2中的Team_Id相等,则Team_1 =加尔各答骑士车手 我也想对Team_2重复相同的过程 请帮忙。

df_1
       Match_Id Over_Id     Ball_Id     Runs_Scored     Team_1  Team_2  Match_Date  Season_Id
106229  829710  1             1             0              1      7     2015-04-08  8
106230  829710  1             1             1              1      7     2015-04-08  8
106231  829710  1             2             1              1      7     2015-04-08  8
106232  829710  1             3             1              1      7     2015-04-08  8
106233  829710  1             3             0              1      7     2015-04-08  8
...     ...     ...     ...     ...     ...     ...     ...     ...
119425  829828  20            4             2              7      3     2015-05-24  8
119426  829828  20            5             0              7      3     2015-05-24  8
119427  829828  20            5             6              7      3     2015-05-24  8
119428  829828  20            6             0              7      3     2015-05-24  8
119429  829828  20            6             4              7      3     2015-05-24  8   ```

df_2
    Team_Id     Team_Name
0   1   Kolkata Knight Riders
1   2   Royal Challengers Bangalore
2   3   Chennai Super Kings
3   4   Kings XI Punjab
4   5   Rajasthan Royals
5   6   Delhi Daredevils
6   7   Mumbai Indians
7   8   Deccan Chargers
8   9   Kochi Tuskers Kerala
9   10  Pune Warriors
10  11  Sunrisers Hyderabad
11  12  Rising Pune Supergiants
12  13  Gujarat Lions```

Then my Output will be 

```First row of df_1 will be as following
106229  829710  1             1             0              Kolkata Knight Riders      7     2015-04-08  8```

1 个答案:

答案 0 :(得分:1)

尝试:

df1.Team_1.update(df1.Team_1.map(df2.set_index('Team_Id').Team_Name))