You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas中清理数据列的'-'与'U'并解决类型错误?

问题描述

我的Pandas DataFrame中有一列名为Last Form,该列包含数字、符号-和字母U,示例数据如下:

1
3
U
4
-
5
U

我想要移除其中的-和U,尝试过以下代码:

df['Last Form'] = df['Last Form'].replace('U', '')
df.replace('-', 0, inplace=True)

但使用>=2过滤结果时,持续出现错误:

TypeError: '>=' not supported between instances of 'str' and 'int'
解决方法

出现这个错误的核心原因是处理后的列仍然是字符串类型,无法直接与整数进行比较。需要先将列转换为数值类型,同时妥善处理非数值内容,推荐两种可靠的处理方式:

方法一:用pd.to_numeric统一转换

该方法可自动将非数值内容转为NaN,填充为0后再转为整数类型,兼容性更强:

import pandas as pd

# 替换'U'为空字符串,再用to_numeric将无法转换的内容转为NaN
df['Last Form'] = pd.to_numeric(df['Last Form'].replace('U', ''), errors='coerce')
# 将NaN替换为0,并转换为整数类型
df['Last Form'] = df['Last Form'].fillna(0).astype(int)

处理完成后,使用df[df['Last Form'] >= 2]过滤数据就不会报错了。

方法二:批量替换后强制转换

如果确认仅存在U和-两种非数值内容,可直接批量替换后转换类型:

# 批量替换'U'为空、'-'为0,再转为整数
df['Last Form'] = df['Last Form'].replace({'U': '', '-': 0}).astype(int)

注意:若替换后存在空字符串,astype(int)会报错,因此该方法仅适用于明确非数值内容范围的场景。

内容的提问来源于stack exchange,提问作者liambh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 08:07:10