我有一个880184 * 1数据帧,唯一的列是整数对象或字符串对象。我想将所有字符串对象更改为数字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
现在的问题是数字和字符串都是“对象”类型,我不知道如何将类似对象的字符串更改为0,如下所示:
index column
..... ......
23155 0
23156 20323
23157 0
23158 19090
23159 0
23160 20474
另一个问题是样本大小太大,使得用于循环来逐行修复的时间太长。我想使用类似:
df.loc[df.column == ...] = 0
您可以通过pd.to_numeric
和传递将类型转换为数字,errors='coerce'
这样一来您将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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句