convert some columns to float

Viewed 358

I want to convert multiple columns from strings to float
I tried:

df[1,4,7,10,13]= pd.to_numeric(df[1,4,7,10,13], downcast="float")

or:

df[1,4,7,10,13]= df[1,4,7,10,13].astype(float)

but none of these works. I want to actually convert all the 1+3*x columns to float. anyone has idea?

2 Answers

Try creating the column numbers using range and accessing via iloc.

import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3], 'B': [1, 2, 3],
                   'C': [1, 2, 3], 'D': [1, 2, 3],
                   'E': [1, 2, 3], 'F': [1, 2, 3],
                   'G': [1, 2, 3], 'H': [1, 2, 3],
                   'I': [1, 2, 3], 'J': [1, 2, 3]})

columns_numbers = list(range(1, len(df.columns), 3))
df.iloc[:, columns_numbers] = df.iloc[:, columns_numbers].astype(float)
print(columns_numbers)
print(df)

Output:

[1, 4, 7]
   A    B  C  D    E  F  G    H  I  J
0  1  1.0  1  1  1.0  1  1  1.0  1  1
1  2  2.0  2  2  2.0  2  2  2.0  2  2
2  3  3.0  3  3  3.0  3  3  3.0  3  3
df[[1, 4, 7, 10, 13]] = set(map(lambda i: tuple(map(float, df[i])), df[[1, 4, 7, 10, 13]]))

This you can do with pure python.

Related