如何使用正则表达式将 Pandas 中的一列拆分为多列? [英] How to split one column into multiple columns in Pandas using regular expression?

查看:144
本文介绍了如何使用正则表达式将 Pandas 中的一列拆分为多列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我有这样的家庭住址:

For example, if I have a home address like this:

马里兰州切维蔡斯朝圣大道 71 号

在名为地址"的列中.我想分别将其拆分为街道"、城市"、州"列.

in a column named 'address'. I would like to split it into columns 'street', 'city', 'state', respectively.

使用 Pandas 实现这一目标的最佳方法是什么?

What is the best way to achieve this using Pandas ?

我试过 df[['street', 'city', 'state']] = df['address'].findall(r"myregex").

但是我得到的错误是使用可迭代的设置时必须具有相等的 len 键和值.

感谢您的帮助:)

推荐答案

您可以使用 split 通过正则表达式 ,\s+(, 和一个或多个空格):

You can use split by regex ,\s+ (, and one or more whitespaces):

#borrowing sample from `Allen`
df[['street', 'city', 'state']] = df['address'].str.split(',\s+', expand=True)
print (df)
                              address id             street          city  \
0  71 Pilgrim Avenue, Chevy Chase, MD  a  71 Pilgrim Avenue   Chevy Chase   
1         72 Main St, Chevy Chase, MD  b         72 Main St   Chevy Chase   

  state  
0    MD  
1    MD  

如果需要删除列 address 添加 drop:

And if need remove column address add drop:

df[['street', 'city', 'state']] = df['address'].str.split(',\s+', expand=True)
df = df.drop('address', axis=1)
print (df)
  id             street         city state
0  a  71 Pilgrim Avenue  Chevy Chase    MD
1  b         72 Main St  Chevy Chase    MD

这篇关于如何使用正则表达式将 Pandas 中的一列拆分为多列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆