Home > OS >  Running loop on all columns with pipe
Running loop on all columns with pipe

Time:08-30

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?

CodePudding user response:

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
  • Related