pandas DataFrame的bua列处理:混合单位转纯平方英尺数值
Pandas bua列单位换算处理方案
实现逻辑
- 用正则表达式从原字符串中匹配提取面积数值和单位类型
- 按照1平方码=9平方英尺的换算规则统一单位为平方英尺
- 最终输出纯数值类型的bua列
可直接运行代码
# 从原bua列提取面积数值和单位两列中间数据 df[['area_value', 'unit_type']] = df['bua'].str.extract(r'Built-up Area (\d+) Sq (Yards|Feet)') # 将提取的数值字符串转为整型,如有小数需求可替换为astype(float) df['area_value'] = df['area_value'].astype(int) # 单位换算后覆盖原bua列,得到纯数值的平方英尺数据 df['bua'] = df.apply(lambda row: row['area_value'] * 9 if row['unit_type'] == 'Yards' else row['area_value'], axis=1) # 清理中间生成的辅助列 df.drop(columns=['area_value', 'unit_type'], inplace=True)
效果说明
处理后原样本中的Built-up Area 97 Sq Yards会转为数值873,Built-up Area 1500 Sq Feet会转为数值1500,完全符合需求。
内容的提问来源于stack exchange,提问作者Kunal Parihar
相关产品推荐
相关产品推荐

