I have a Pandas data frame that has the following columns: foo and bar. foo values are integers and bar values are strings. For each row, if the value of bar is some particular value, say, ‘ABC’, then I want to set the value of the foo column (for that row) to its current value minus one.
For example, I want to convert this data frame:
| foo | bar |
|---|---|
| 98 | ‘ABC’ |
| 53 | ‘DEF’ |
| 22 | ‘ABC’ |
| 34 | ‘FGH’ |
converted to this:
| foo | bar |
|---|---|
| 97 | ‘ABC’ |
| 53 | ‘DEF’ |
| 21 | ‘ABC’ |
| 34 | ‘FGH’ |
How is this done?
>Solution :
You can do this via the .loc on dataframe:
CONSTANT_VAL = 1
df.loc[df['bar'] == 'ABC', 'foo'] -= CONSTANT_VAL