My original DataFrame looks like this:
windcodes | name | matu | CLAUSE | WEIGHTEDRT |
---|---|---|---|---|
163197.SH | shangguo comp | 2.9248 | NO | 2.582 |
154563.SH | guosheng comp | 2.886 | YES | 2.773 |
789645.IB | guoyou comp | YES | 3.098 | |
1880260.IB | shagui comp | YES | 2.657 |
What I want to do now is that for every row if CLAUSE equal to yes, then substitute the matu value of that row with its WEIGHTEDRT value, and if CLAUSE equal to NO then just leave the original matu and weightedrt as they were.
I wish my outcome DataFrame to be look like this:
windcodes | name | matu | CLAUSE | WEIGHTEDRT |
---|---|---|---|---|
163197.SH | shangguo comp | 2.9248 | NO | 2.582 |
154563.SH | guosheng comp | 2.773 | YES | 2.773 |
789645.IB | guoyou comp | 3.098 | YES | 3.098 |
1880260.IB | shagui comp | 2.657 | YES | 2.657 |
CodePudding user response:
clause_yes = df['CLAUSE'] == 'YES'
df.loc[clause_yes, 'matu'] = df.loc[clause_yes, 'WEIGHTEDRT']
CodePudding user response:
You can use pd.where
here:
df.assign(matu = df.matu.where(df.CLAUSE.eq('NO'), df.WEIGHTEDRT))
windcodes name matu CLAUSE WEIGHTEDRT
0 163197.SH shangguo comp 2.9248 NO 2.582
1 154563.SH guosheng comp 2.7730 YES 2.773
2 789645.IB guoyou comp 3.0980 YES 3.098
3 1880260.IB shagui comp 2.6570 YES 2.657
You can also use np.where
too:
df.assign(matu = np.where(df.CLAUSE.eq('YES'), # condition
df.WEIGHTEDRT, # result if True
df.matu)) # result if False
windcodes name matu CLAUSE WEIGHTEDRT
0 163197.SH shangguo comp 2.9248 NO 2.582
1 154563.SH guosheng comp 2.7730 YES 2.773
2 789645.IB guoyou comp 3.0980 YES 3.098
3 1880260.IB shagui comp 2.6570 YES 2.657