简体   繁体   中英

Multiply an entire dataframe column based on conditions from another dataframe

I have two dataframes df1 and df2

df1

name          | letter 
john (345)    | A         
patrick (539) | A       
drew (245)    | A            
john (591)    | B         
patrick (912) | B        
drew (553)    | B        

df2

john (345) | patrick (539) | drew (245) | john (591) | patrick (912) | drew (553)
1            1               1            1            1               1                     
2            2               2            2            2               2   
3            3               3            3            3               3   
4            4               4            4            4               4   
5            5               5            5            5               5   
6            6               6            6            6               6  

I want to multiple the rows in df2 by 2 when the names equal letter "B"

Desired result:

john (345) | patrick (539) | drew (245) | john (591) | patrick (912) | drew (553)
1            1               1            2            2               2                     
2            2               2            4            4               4   
3            3               3            6            6               6   
4            4               4            8            8               8   
5            5               5            10           10              10   
6            6               6            12           12              12  

The following might work

df2 * df1.set_index("name")["letter"].map({"A": 1, "B": 2})

In straightforward way:

names = df1[df1.letter == 'B']['name']  # filtering the needed names
df2[names] = df2[names] * 2

   john (345)  patrick (539)  drew (245)  john (591)  patrick (912)  drew (553)
0           1              1           1           2              2           2
1           2              2           2           4              4           4
2           3              3           3           6              6           6
3           4              4           4           8              8           8
4           5              5           5          10             10          10
5           6              6           6          12             12          12

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