DRPR
DRPR

Reputation: 269

pd.to_numeric not working

I am facing a weird problem with pandas.

I donot know where I am going wrong?

enter image description here

But when I am creating a new df, there seems to be no problem. like

enter image description here

Any idea why?

Edit :

sat=pd.read_csv("2012_SAT_Results.csv")
sat.head()
#converted columns to numeric types
sat.iloc[:,2:]=sat.iloc[:,2:].apply(pd.to_numeric,errors="coerce")
sat.dtypes
sat_1=sat.iloc[:,2:].apply(pd.to_numeric,errors="coerce")
sat_1.head()

Upvotes: 3

Views: 1371

Answers (1)

elPastor
elPastor

Reputation: 8956

The fact that you can't apply to_numeric directly using .iloc appears to be a bug, but to get the same results that you're looking for (applying to_numeric to multiple columns at the same time), you could instead use:

df = pd.DataFrame({'a':['1','2'],'b':['3','4']})

# If you're applying to entire columns
df[df.columns[1:]] = df[df.columns[1:]].apply(pd.to_numeric, errors = 'coerce')

# If you want to apply to specific rows within columns
df.loc[df.index[1:], df.columns[1:]] = df.loc[df.index[1:], df.columns[1:]].apply(pd.to_numeric, errors = 'coerce')

Upvotes: 2

Related Questions