python将字符串对象更改为数字

python将字符串对象更改为数字,python,pandas,Python,Pandas,我有一个880184*1数据帧,唯一的列是integer对象或string对象。我想将所有字符串对象更改为数字0。如下所示: index column ..... ...... 23155 WILLS ST / MIDDLE POINT RD 23156 20323 23157 400 Block of BELLA VISTA WY 23158

我有一个880184*1数据帧,唯一的列是integer对象或string对象。我想将所有字符串对象更改为数字0。如下所示:

index               column
.....               ......
23155     WILLS ST / MIDDLE POINT RD
23156                          20323
23157    400 Block of BELLA VISTA WY
23158                          19090
23159     100 Block of SAN BENITO WY
23160                          20474
index                          column
.....                          ......
23155                            0
23156                          20323
23157                            0
23158                          19090
23159                            0
23160                          20474
现在的问题是数字和字符串都是“对象”类型,我不知道如何将类似字符串的对象更改为0,如下所示:

index               column
.....               ......
23155     WILLS ST / MIDDLE POINT RD
23156                          20323
23157    400 Block of BELLA VISTA WY
23158                          19090
23159     100 Block of SAN BENITO WY
23160                          20474
index                          column
.....                          ......
23155                            0
23156                          20323
23157                            0
23158                          19090
23159                            0
23160                          20474
另一个问题是样本量太大,使得循环用于逐行修复的时间太长。我想使用类似于:

df.loc[df.column == ...] = 0

您可以使用将类型转换为数字,并传递
errors='concurve'
,这样,对于无法转换为数字的类型,您将获得
NaN
。最后,您可以将
NaN
s替换为零:

df["column"] = pd.to_numeric(df["column"], errors="coerce").fillna(0)
Out[15]: 
0        0.0
1    20323.0
2        0.0
3    19090.0
4        0.0
5    20474.0
Name: column, dtype: float64
如果需要整数值,请在末尾添加
astype('int64')

df["column"] = pd.to_numeric(df["column"], errors="coerce").fillna(0).astype("int64")
Out[16]: 
0        0
1    20323
2        0
3    19090
4        0
5    20474
Name: column, dtype: int64

尝试使用int()函数将所有内容转换为整数。 无法转换字符串,因此引发错误。将其打包成一个“尝试”循环,即可完成设置

像这样:

def converter(currentRowObj):
    try:
        obj = int(currentRowObj)
    except:
        obj = 0
    return obj

欢迎来到StackOverflow!这不是一个编码网站,你可以要求别人为你做的工作。这是一个问答网站,致力于收集一个人所不能回答的问题,并提供有用的答案。你必须展示你的努力,你的非工作代码,并制定一个明确的问题,你想让我们回答什么。嗨,对不起,我不想让别人为我工作。我只是被困在这一点上,不知道如何解决它。