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

Python Pandas Divide multiple columns by a value for the rows that match a condition in another column

I have a data like below in a pandas dataframe but there are over 500 columns and for columns 2-500+ I need to divide only the rows where in column 0 the value is ‘dog’ by 100.

0       1       2       3
cat    2019   19.80   96.28
cat    2022   19.50   66.80
dog    2022   21.10   57.70
dog    2021   21.50   42.85

The expected output is below:

0       1       2       3
cat    2019   19.80    96.28
cat    2022   19.50    66.80
dog    2022   0.211    0.577
dog    2021   0.215    0.4285

I have the following code which works to divide it by 100 for those specific rows and columns but it removes columns 0 and 1 and any rows that aren’t ‘dog’.

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

df=df[df[0].str.contains("dog")].loc[:,2:len(r2.columns)-1].div(100)

How do I keep the full dataframe and apply this division on those specific rows and columns?

>Solution :

Hate it when people post the correct answer in the comments, Imma just post the same thing as I thought as a real answer. Small credit for @mozway cuz’ otherwise I would’ve needed to rummage in my brain how to do so.

df.loc[df[0].str.contains("dog"), 2:] /= 100

Have a good day.

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