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

Pandas中拆分房产数据列:提取卧室数量与房产类型至新列

解决方案

你的问题在于str[:1]仅能提取字符串第一个字符,仅适用于个位数卧室数,且无法拆分出房产类型。以下是两种更可靠的实现方式:

方法一:按固定格式拆分(适用于严格"数字 bedroom 类型"格式)

利用字符串拆分函数str.split()按空格分割列内容,直接提取对应部分:

# 按空格拆分property列,拆分为3列
split_result = df['property'].str.split(' ', expand=True)
# 提取卧室数量(第一列)
df['bedroom_no'] = split_result[0]
# 提取房产类型(第三列)
df['property_type'] = split_result[2]

如果需要将卧室数量转为整数类型,可添加:

df['bedroom_no'] = df['bedroom_no'].astype(int)

方法二:正则表达式提取(兼容性更强)

如果数据中存在卧室数为两位数(如"10 bedroom house")或房产类型带空格(如"2 bedroom seaside apartment")的情况,用正则表达式提取更灵活:

# 正则匹配开头的数字、跳过bedroom/bedrooms、提取剩余内容作为房产类型
df[['bedroom_no', 'property_type']] = df['property'].str.extract(r'^(\d+) bedroom(?:s)? (.+)$', expand=True)
# 可选:转换卧室数为整数
df['bedroom_no'] = df['bedroom_no'].astype(int)

正则表达式说明:

  • ^(\d+):匹配字符串开头的1个或多个数字(即卧室数量)
  • bedroom(?:s)?:匹配"bedroom"或"bedrooms",(?:s)?是不捕获匹配组,避免生成多余列
  • (.+)$:匹配剩余所有内容作为房产类型,支持带空格的类型名称

内容的提问来源于stack exchange,提问作者Robin Baggott la Velle

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 06:45:47