从DataFrame列中提取特定字符/文本

时间:2019-07-30 14:49:10

标签: python string pandas dataframe

我正在尝试从Dataframe的mail列中获取电子邮件提供者,并创建一个名为“ Mail_Provider”的新列。例如,从a@gmail.com获取gmail并将其存储在“ Mail_Provider”列中。我也想从“电话”列中提取“国家ISD”,并为此创建一个新列。除了正则表达式外,还有其他直接/简单的方法。

data = pd.DataFrame({"Name":["A","B","C"],"mail": 
["a@gmail.com","b@yahoo.com","c@gmail.com"],"Adress": 
["Adress1","Adress2","Adress3"],"Phone":["+91-1234567890","+88- 
0987654321","+27-2647589201"]})

Name   mail        Adress       Phone

A    a@gmail.com   Adress1  +91-1234567890
B    b@yahoo.com   Adress2  +88-0987654321
C    c@gmail.com   Adress3  +27-2647589201

预期结果:-

Name   mail        Adress       Phone        Mail_Provider   ISD

A    a@gmail.com   Adress1  +91-1234567890    gmail           91
B    b@yahoo.com   Adress2  +88-0987654321    yahoo           88
C    c@gmail.com   Adress3  +27-2647589201    gmail           27

3 个答案:

答案 0 :(得分:9)

正则表达式非常简单:

data['Mail_Provider'] = data['mail'].str.extract('\@(\w+)\.')

data['ISD'] = data['Phone'].str.extract('\+(\d+)-')

如果您真的想避免使用正则表达式,那么@Eva的答案就是解决方法。

答案 1 :(得分:4)

lambda函数将起作用

data['Mail_Provider'] = data['mail'].apply(lambda x: x.split("@")[1].split(".")[0])

data['ISD'] = data['Phone'].apply(lambda x: x.split("+")[1].split("-")[0])

答案 2 :(得分:4)

混合方法(正则表达式和简单切片):

In [693]: df['Mail_Provider'] = df['mail'].str.extract('@([^.]+)')

In [694]: df['ISD'] = df['Phone'].str[1:3]

In [695]: df
Out[695]: 
  Name         mail   Adress           Phone Mail_Provider ISD
0    A  a@gmail.com  Adress1  +91-1234567890         gmail  91
1    B  b@yahoo.com  Adress2  +88-0987654321         yahoo  88
2    C  c@gmail.com  Adress3  +27-2647589201         gmail  27