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

如何删除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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 20:40:25