My imports are:
import pandas as pd
import numpy as np
from pandas.api.types import is_numeric_dtype
I created a pandas dataframe (named df) that looks like this:
state initial_temp final_temp
0 Cold 48.0 88.1
1 hot 80.7 30.0
2 hot 140.2 25.0
3 hot 59.8 25.0
4 hot 80.0 25.0
All the columns have dtypes object, however, the only column that should have that dtype is the state column. I am trying to convert all the actual numeric columns (initial and final temp) to numerical dtypes and ignore/leave out the state column. This is mainly for pedagogical purposes.
My current attempt at this is:
def datatype_converter(df):
col_list = []
for column in df.columns:
col_list.append(column)
for i in range(len(col_list)):
if is_numeric_dtype(df[col_list.pop()]):
df.apply(pd.to_numeric, errors = 'coerce') # coerce invalid values to nan.
else:
pass
return df