在 pandas 数据框列中查找非数值
Find non-numeric values in pandas dataframe column
我在包含数字和字符串的数据框中得到了一个列。所以我通过 df.column.replace(["A", "B", "C", "D"], [1, 2, 3, 4], inplace=True)
.
用数字替换了字符串
但是该列仍然是 dtype "object"。我无法对列进行排序(TypeError 错误:'str' 和 'int' 实例之间不支持“<”)。
现在我如何识别那些是字符串的数字?我尝试了 print(df[pd.to_numeric(df['column']).isnull()])
并且它按预期返回了一个空数据框。但是我读到这在我的情况下不起作用(实际数字保存为字符串)。那么如何识别保存为字符串的那些数字呢?
如果列只包含实数(int 或 float),它会自动更改为 dtype int 或 float,我说得对吗?
谢谢!
你可以改变数据类型
df.column.dtype=df.column.astype(int)
您可以将 pd.to_numeric
与类似的东西一起使用:
df['column'] = pd.to_numeric(df['column'], errors='coerce')
对于 errors
参数,您几乎没有选择,请参阅参考文档 here
我在包含数字和字符串的数据框中得到了一个列。所以我通过 df.column.replace(["A", "B", "C", "D"], [1, 2, 3, 4], inplace=True)
.
但是该列仍然是 dtype "object"。我无法对列进行排序(TypeError 错误:'str' 和 'int' 实例之间不支持“<”)。
现在我如何识别那些是字符串的数字?我尝试了 print(df[pd.to_numeric(df['column']).isnull()])
并且它按预期返回了一个空数据框。但是我读到这在我的情况下不起作用(实际数字保存为字符串)。那么如何识别保存为字符串的那些数字呢?
如果列只包含实数(int 或 float),它会自动更改为 dtype int 或 float,我说得对吗?
谢谢!
你可以改变数据类型
df.column.dtype=df.column.astype(int)
您可以将 pd.to_numeric
与类似的东西一起使用:
df['column'] = pd.to_numeric(df['column'], errors='coerce')
对于 errors
参数,您几乎没有选择,请参阅参考文档 here