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

如何在Python中将含英尺英寸数据的Object类型DataFrame转换为float类型英寸数据

嘿,这个需求我熟!之前处理过好几个类似的身高数据转换场景,给你几个实用的方案,根据你的数据格式选就行~

方案1:针对规范格式的字符串拆分法

如果你的身高数据格式非常统一(比如都是5'10"这种英尺加单引号、英寸加双引号的形式),直接拆分字符串计算最高效:

import pandas as pd

# 假设你的DataFrame是df,身高列名为height
df = pd.DataFrame({'height': ['5\'10"', '6\'2"', '4\'11"', '5\'5"']})

# 拆分英尺和英寸部分
df[['feet', 'inches']] = df['height'].str.split('\'', expand=True)
# 移除英寸部分的双引号并转为数值型
df['inches'] = df['inches'].str.replace('"', '').astype(float)
# 计算总英寸:1英尺=12英寸,所以总英寸=英尺*12 + 英寸
df['height_in_inches'] = df['feet'].astype(float) * 12 + df['inches']
# 可以删掉中间生成的feet和inches列(可选)
df = df.drop(['feet', 'inches'], axis=1)

如果你的数据格式是5 ft 10 in这种,只需要把str.split('\'')改成str.split(' ft '),再用str.replace(' in', '')清理英寸部分的后缀就行~

方案2:灵活适配多种格式的正则提取法

如果数据格式不统一(比如混着5'10"、5 ft 8 in、5'9甚至6英尺3英寸),用正则表达式提取数字会更靠谱:

import pandas as pd
import re

def convert_to_inches(height_str):
    # 提取字符串里的所有数字,第一个是英尺,第二个是英寸(没有的话默认0)
    nums = re.findall(r'\d+', str(height_str))
    if not nums:
        return None  # 处理空值或无效数据
    feet = float(nums[0])
    inches = float(nums[1]) if len(nums) >= 2 else 0.0
    return feet * 12 + inches

# 应用函数到身高列
df['height_in_inches'] = df['height'].apply(convert_to_inches).astype(float)

额外提示:处理异常数据

如果你的数据里有格式错误或者缺失值,给函数加个异常捕获会更稳健:

def convert_to_inches_safe(height_str):
    try:
        nums = re.findall(r'\d+', str(height_str))
        if not nums:
            return None
        feet = float(nums[0])
        inches = float(nums[1]) if len(nums) >= 2 else 0.0
        return feet * 12 + inches
    except Exception as e:
        print(f"处理数据 {height_str} 时出错: {e}")
        return None

df['height_in_inches'] = df['height'].apply(convert_to_inches_safe).astype(float)

这样转换后,height_in_inches列就是float类型的英寸数据啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 20:34:04