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
CodePudding user response:
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
CodePudding user response:
The following might work
df2 * df1.set_index("name")["letter"].map({"A": 1, "B": 2})