Running loop on all columns with pipe

Question:

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?

Asked By: Bogaso

||

Answers:

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
Answered By: mitoRibo
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.