Subtracting a constant value from one column when condition on another column holds


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?

Asked By: Paul Reiners



In [2]: df
   foo  bar
0   98  ABC
1   53  DEF
2   22  ABC
3   34  FGH

In [3]: df.loc['ABC', 'foo'] = df['ABC']['foo']-1

In [4]: df
   foo  bar
0   97  ABC
1   53  DEF
2   21  ABC
3   34  FGH
Answered By: inspectorG4dget

You can do this via the .loc on dataframe:

df.loc[df['bar'] == 'ABC', 'foo'] -= CONSTANT_VAL
Answered By: Sanyam Khurana

.loc and np.where both can work as a possible solution here.

np.where works like an if-else statement, where it checks whether the condition is met, which in this case is df['bar'] == 'ABC', and if its true, subtract 1 from df[‘foo’], else dont do anything.

df['foo'] = np.where(df['bar']=='ABC', df['foo']-1, df['foo'])
Answered By: P. Shroff
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.