Reputation: 11
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
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