如何删除Pandas DataFrame列中的浮点类型值?
解决Pandas DataFrame中删除指定列浮点类型值的问题
问题分析
你之前的两种方法没达到预期的原因:
astype(str)只是将所有类型强制转为字符串,比如浮点值1.0会变成字符串"1.0",导出CSV后仍会显示该内容,并非删除浮点值。- 原
mask写法有误:Python中逻辑或需用or而非位运算符|,且mask是将符合条件的元素替换为NaN,若CSV导出时NaN被渲染为其他内容,也会导致看起来还有浮点值残留。
针对性解决方案
根据需求选择以下任意一种:
1. 删除该列值为浮点类型的整行
如果需要直接移除包含浮点值的行:
# 筛选出store_and_fwd_flag列不是浮点类型的行 df = df[~df['store_and_fwd_flag'].apply(lambda x: isinstance(x, float))]
2. 将浮点类型值替换为空字符串(保留行)
如果只想清除浮点值但保留行,可将浮点值替换为空字符串:
df['store_and_fwd_flag'] = df['store_and_fwd_flag'].apply( lambda x: x if not isinstance(x, float) else '' )
补充:同时过滤int和float类型
如果需要同时删除该列中int和float类型的值(或对应的行),只需调整判断条件:
# 删除包含int/float值的行 df = df[~df['store_and_fwd_flag'].apply(lambda x: isinstance(x, (int, float)))] # 替换int/float值为空字符串 df['store_and_fwd_flag'] = df['store_and_fwd_flag'].apply( lambda x: x if not isinstance(x, (int, float)) else '' )
验证方法
处理后可以用以下代码确认类型分布:
print(df['store_and_fwd_flag'].apply(type).value_counts())
内容的提问来源于stack exchange,提问作者DeBe
相关产品推荐
相关产品推荐

