我的数据框中有以下列:
Column1 Column2 Column3 Column4
a 1 2 a
1 2 a c
b 3 c d
3 2 1 b
4 2 1 a
c 1 d a
这些列的类型是object
,我想将Column1
、Column2
和Column3
转换为数字类型 int8
,同时保留 Column4
作为类型对象。为此,我尝试使用 pd.to_numeric(data.Column1)
(我计划在使用 Column2
和 Column3
后执行相同操作>) 但我收到以下错误:
ValueError:无法解析位置 0 处的字符串“a”
发生这种情况的原因很明显。我想知道是否有任何方法可以让我摆脱这 3 列中由字符串组成的行,所以在那之后,我会得到:
Column1 Column 2 Column 3 Column 4
3 2 1 b
4 2 1 a
有办法实现吗?或者还有其他方法可以让我这样做吗?
编辑:我已检查 Remove non-numeric rows in one column with pandas 中的问题,但这并没有解决我的问题,因为我的数据集中有更多的列,而不仅仅是两列,其中一列我不想将其转换为数字。
最佳答案
使用apply
与 to_numeric
将非数字替换为缺失值,然后按 dropna
删除 NaN
行最后转换为整数:
df = df.apply(lambda x: pd.to_numeric(x, errors='coerce')).dropna().astype(int)
print (df)
Column1 Column2 Column3
3 3 2 1
4 4 2 1
详细信息:
print (df.apply(lambda x: pd.to_numeric(x,errors='coerce')))
Column1 Column2 Column3
0 NaN 1.0 2.0
1 1.0 2.0 NaN
2 NaN NaN NaN
3 3.0 2.0 1.0
4 4.0 2.0 1.0
5 NaN 1.0 NaN
编辑:
另一个解决方案是检查 DataFrame.all
是否缺少值与 boolean indexing
:
cols = ['Column1','Column2','Column3']
#define columns for check numeric
mask = df[cols].apply(lambda x: pd.to_numeric(x, errors='coerce')).notnull().all(axis=1)
#filtering
df = df[mask]
#converting to integers
df[cols] = df[cols].astype(int)
print (df)
Column1 Column2 Column3 Column4
3 3 2 1 b
4 4 2 1 a
print (df.dtypes)
Column1 int32
Column2 int32
Column3 int32
Column4 object
dtype: object
关于python - 如何在也有字符串的列数据框中保留数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52180879/