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

How to change values in multiple pandas dataframe columns?

Suppose I have a dataframe like
this.

I want to normalize the data in the ‘cholesterol’ and ‘gluc’ columns, such that if the value is 1 then it becomes 0, and if it’s greater than 1 then it becomes 1 (basically 0 is always good and 1 is always bad). I can do this to each column individually with np.where(), however I’m curious if there’s a way to change both columns with a single command, but I haven’t found anything related online.

I can start by slicing the columns with df.loc[:, ['cholesterol', 'gluc']], which creates a view of the two columns. Is there a way to change this view with one command or do I still have to change each column individually?

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

>Solution :

Try like this :

df.loc[:, ['cholesterol', 'gluc']] = np.where(df.loc[:, ['cholesterol', 'gluc']] > 1, 1, 0)
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