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

Running loop on all columns with pipe

I want to run a for loop with all columns starting from 1. Below is my code

import pandas as pd
dat = pd.DataFrame({'X' : ['X', 'Y'], 'A' : [1,2], 'B' : [3,4]})
for i in range(1, 3) :
    dat.iloc[:, i] = dat.iloc[:, i].astype(float)

While this is fine, I want to use pipe method to achieve the same in a concise way. Here the applied function is simple astype, however I should be able to use any custom function including lambda.

Is there any way to perform 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

>Solution :

Another way without iloc. I don’t think pipe is useful for this problem

import pandas as pd
dat = pd.DataFrame({'X' : ['X', 'Y'], 'A' : [1,2], 'B' : [3,4]})
cols = dat.columns[1:]
dat[cols] = dat[cols].apply(lambda v: v.astype(float))
dat
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