Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading