简体   繁体   中英

how to compare two columns in different dataframe pandas and replacing values with other columns

I want to compare 'Team_1' in df_1 (dataframe) with 'Team_Id' in df_2 (Dataframe) Whenever I find a match, I want to replace the value of Team_1 in df_1 with corresponding value in Team_Name in df_2. So I can proceed to work with df_1

For example:if Team_1 = 1 in df_1 and Team_Id in df_2 are equal, then Team_1 = Kolkata Knight Riders I also want to repeat the same process with Team_2 Please help.

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```

尝试这个 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM