Jamie
Jamie

Reputation: 47

How do change a data type of all columns in python

I am using pandas data frames. The data contains 3032 columns. All the columns are 'object' datatype. How do I convert all the columns to 'float' datatype?

enter image description here

enter image description here

Upvotes: 1

Views: 54

Answers (2)

Ivan Calderon
Ivan Calderon

Reputation: 620

If you are reading the df from a file you can do the same when reading using converters in case you want to apply a customized function, or using dtype to specify the data type you want.

Upvotes: 0

jezrael
jezrael

Reputation: 862581

If need convert integers and floats columns use to_numeric with DataFrame.apply for apply for all columns:

df = df.apply(pd.to_numeric)

working same like:

df = df.apply(lambda x: pd.to_numeric(x))

If some columns contains strings (so converting failed) is possible add errors='coerce' for repalce it to missing values NaN:

df = df.apply(pd.to_numeric, errors='coerce')

Upvotes: 3

Related Questions