首页 > 解决方案 > pd.to_numeric 不工作

问题描述

我面临着一个奇怪的熊猫问题。

我不知道我哪里出错了?

在此处输入图像描述

但是当我创建一个新的df时,似乎没有问题。喜欢

在此处输入图像描述

知道为什么吗?

编辑 :

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

标签: python-3.xpandas

解决方案


您不能to_numeric直接应用的事实.iloc似乎是一个错误,但要获得您正在寻找的相同结果(同时应用于to_numeric多个列),您可以改为使用:

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

推荐阅读