Suppose we have
>>> df.dtype
Name object
Height object
Weight object
Age object
Job object
Is there any simple way to covert all columns except Name and Job columns with .to_numeric() method?
I have tried but it doesn't work
df.iloc[df.columns != Name & df.columns != Job] = pd.to_numeric(df.iloc[df.columns != Name & df.columns != Job], errors='coerce')
The simplest way that comes to my mind would be to make a list of all the columns except Name and Job and then iterate pandas.to_numeric
over them:
cols=[i for i in df.columns if i not in ["Name","Job"]]
for col in cols:
df[col]=pd.to_numeric(df[col])
Edit:
If you absolutely want to use numbers instead of columns names and already know at which indice they are:
for i in [i for i in list(range(len(df.columns))) if i not in [0,4]]:
df.iloc[:,i]=pandas.to_numeric(df.iloc[:,i])
That's more complicated than necessary though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With