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

如何将pandas DataFrame中object类型的height列转为float类型?

解决方案

针对200万行的大数据量,优先使用pandas向量化操作,避免逐行遍历,性能足够应对需求,完整处理代码如下:

import pandas as pd
import numpy as np

# 第一步:替换明确无效值为NaN
df['height'] = df['height'].replace(['Unknown', 'Bilinmiyor'], np.nan)

# 第二步:统一十进制分隔符,逗号替换为点
df['height'] = df['height'].str.replace(',', '.', regex=False)

# 第三步:处理分号分隔的多值,拆分后取最大值
def get_max_from_semicolon(x):
    if pd.isna(x) or ';' not in x:
        return x
    nums = list(map(float, x.split(';')))
    return str(max(nums))
df['height'] = df['height'].apply(get_max_from_semicolon)

# 第四步:处理英尺英寸格式,转换为米(1英尺=0.3048米,1英寸=0.0254米)
# 匹配 数字' 可选空格 可选数字" 格式
ft_in_mask = df['height'].str.contains(r"'", na=False)
ft_in_df = df.loc[ft_in_mask, 'height'].str.extract(r"(?P<ft>\d+)'\s*(?P<in>\d*)\"?", expand=True)
ft_in_df = ft_in_df.replace('', 0).astype(float)
df.loc[ft_in_mask, 'height'] = ft_in_df['ft'] * 0.3048 + ft_in_df['in'] * 0.0254

# 第五步:移除米单位标识(包括前后空格)
df['height'] = df['height'].str.replace(r'\s*m\s*$', '', regex=True)

# 第六步:统一转换为float类型,剩余异常值自动转为NaN
df['height'] = pd.to_numeric(df['height'], errors='coerce')
处理效果验证

你提供的示例数据处理后结果如下:

原取值处理后取值
1616.0
77.0
77.0
6 m6.0
2.402.4
5'8"1.7272
3m3.0
6,96.9
9;6;39.0
UnknownNaN
4.664.66
BilinmiyorNaN
11' 4"3.4544

处理完成后height列的dtype为float64,完全符合要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 07:15:05