基于多个可能的分隔符拆分数据帧中的列

2024-06-26 14:42:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我在pandas的数据框中有一个address列,包含3种类型的信息,即街道、殖民地和城市。在

有三个值有两个可能的分隔符-要么是''或空白,例如它可以是Street1,Colony1,City1或{}。在

我需要将这个列分成三个,分别使用标签'Street''Colony'和{},并相应地将Address列中的值拆分。在

最有效的方法是什么,因为pandassplit函数只允许使用单个分隔符或regex表达式(可能是一个regex表达式,因为我对regex不是很在行)。在


Tags: 数据信息类型pandas表达式address标签街道
3条回答

如果您确定regex中的逗号,或空白 you could use:

^{pr 1}$

Explanation:str.split accepts a pat (pattern) parameter: String or regular expression to split on. If not specified, split on whitespace. Using the fact we can pass a regular expression this becomes an easy task as [ ,]表示,。在

另一种选择是使用' |,',或者如果可以有多个空格'\s+|,'


完整示例:

^{pr2}$

退货:

  address Street Colony City
0   a,b,c      a      b    c
1   a b c      a      b    c

试试这个

df[['Street','Colony','City']] = df.address.apply(lambda x: pd.Series(re.split('\W',x)))

\W将匹配任何非单词字符的字符。见docs

实现这一点的一种方法是使用re.sub合并分隔符,然后在该分隔符上使用str.split来创建新列。在

import pandas as pd 
import re

df = pd.DataFrame({'address':['Street1,Colony1,City1',  'Street2 Colony2 City2']})

location_df = (df.address
                 .apply(lambda x: pd.Series(re.sub(pattern=' |,', 
                                                   repl=',', 
                                                   string=x).split(','), 
                                            index=['street','colony','city']))
                )

相关问题 更多 >