Skip to main content
 首页 » 编程设计

python之如何从 Pandas 的地址中提取公寓

2025年05月04日18duanxz

我有一个相当困惑的数据集,由于手动输入数据,其中有很多不一致和错误。

我正在 pandas 中处理此数据集的地址列。

我想做的是将地址列分成 3 个独立的实体:

1) 地址列

2) 一列街道号码

3) 公寓或单元号列

数据如下所示:

address 
---------------------- 
123 smith street #5234 
5000 john ct 
34 wood st apt# 23 
523 fire road apt #87 
charles way apt. 434 
0987 misty lane unit B  

我已经将街道号码删除到他们自己的列中。为此,我使用了“np.where”并使用了一个简单的逻辑条件,即如果字符串以数字开头,则将它们提取到新的街道列中。

我现在对如何使用公寓号执行此操作感到困惑。

我假设由于不一致,我必须做类似的事情:

df['apt/unit'] = np.where(str contains "apt", extract string starting at "apt" until end, else np.NaN) 
df['apt/unit'] = np.where(str contains "unit", extract string starting at "unit" until end, else np.NaN) 

我必须使用正则表达式来执行此操作吗?如果是这样,解决方法是什么?

除了这种思路还有其他选择吗?

请您参考如下方法:

由于您的 apt/unit 列有多个条件,您可以在此处使用 np.select,如下所示:

# Define our conditions 
conditions = [ 
    df.address.str.contains('apt'), 
    df.address.str.contains('unit'), 
    df.address.str.contains('#') 
] 
 
# Define our choices based on our conditions 
choices = [ 
    df.address.apply(lambda x: x[x.find('apt'):]), 
    df.address.apply(lambda x: x[x.find('unit'):]), 
    df.address.apply(lambda x: x[x.find('#'):]) 
] 
 
# Apply this logic by creating the new column and cleaning up address column 
df['apt/unit'] = np.select(conditions, choices, default = '') 
 
# Clean up our address column 
choices2 = [ 
    df.address.apply(lambda x: x[:x.find('apt')]), 
    df.address.apply(lambda x: x[:x.find('unit')]), 
    df.address.apply(lambda x: x[:x.find('#')]) 
] 
df['address'] = np.select(conditions, choices2, default = df.address) 

输出

print(df) 
 
             address  apt/unit 
0  123 smith street      #5234 
1       5000 john ct           
2        34 wood st    apt# 23 
3     523 fire road    apt #87 
4       charles way   apt. 434 
5   0987 misty lane     unit B