Bharath Sagar
Bharath Sagar

Reputation: 11

How to iterate through a pandas dataframe column and check the datatype of each column and change it another datatype if needed

I have a dataframe "df". I'm trying to access all the columns of the dataframe and check the datatype of each column and if the datatype is "object" i want to change it to float.

I'm trying with the below code, but it is not working:

for colname, coltype in df.dtypes.iteritems():
    if coltype == object:
         df[colname] = df[colname].astype(np.float32)

I don't understand what is wrong here. Can anyone help me out please ?

Upvotes: 1

Views: 3220

Answers (1)

Hussein Awala
Hussein Awala

Reputation: 5096

you can try this code

types={}
for col in df.columns:
    if df[col].dtype == object:
        types[col] = float
    else:
        types[col] = df[col].dtype
df = df.astype(types)

Upvotes: 4

Related Questions