'How to update column value based on another value in pandas
I have the below data frame
| A | B |
|---|---|
| Jan | 10 |
| Feb | 20 |
| Mar | 30 |
| Apr | 20 |
Required Output - I want to check for March from A and get its corresponding value from B and add that value to remaining B values to update the dataframe using pandas
| A | B |
|---|---|
| Jan | 40 |
| Feb | 50 |
| Apr | 50 |
Solution 1:[1]
You can find the value corresponding to 'Mar', add that value to the rest of the df, then drop the row containing 'Mar'
df.loc[df['A'] != 'Mar','B'] += df.loc[df['A'] == 'Mar', 'B'].values
df = df[df['A'] != 'Mar']
Result:
>>> df
A B
0 Jan 40
1 Feb 50
3 Apr 50
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Derek O |
