Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: convert all column from string to number except two?

Tags:

python

pandas

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')

like image 319
Learner132 Avatar asked Dec 19 '22 06:12

Learner132


1 Answers

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.

like image 174
baloo Avatar answered Dec 21 '22 09:12

baloo