设df为数据帧,如下所示:
date text
0 2019-6-7 London is good.
1 2019-5-8 I am going to Paris.
2 2019-4-4 Do you want to go to London?
3 2019-3-7 I love Paris! 我想添加一个列city,它表示text中包含的城市,即
date text city
0 2019-6-7 London is good. London
1 2019-5-8 I am going to Paris. Paris
2 2019-4-4 Do you want to go to London? London
3 2019-3-7 I love Paris! Paris 如何在不使用lambda的情况下完成此操作
发布于 2019-07-09 11:31:36
你可以先匹配确定你有城市列表,然后匹配str.findall
df.text.str.findall('London|Paris').str[0]
Out[320]:
0 London
1 Paris
2 London
3 Paris
Name: text, dtype: object
df['city'] = df.text.str.findall('London|Paris').str[0]发布于 2019-07-09 11:43:50
加上@WenYoBen的方法,如果一个文本中只有巴黎或伦敦中的一个,那么str.extract更好:
regex = '(London|Paris)'
df['city'] = df.text.str.extract(regex)
df
date text city
0 2019-6-7 London is good. London
1 2019-5-8 I am going to Paris. Paris
2 2019-4-4 Do you want to go to London? London
3 2019-3-7 I love Paris! Paris如果你想把你的正则表达式中的所有城市都放在一个文本中,那么str.extractall也是一个选择:
df['city'] = df.text.str.extractall(regex).values
df
date text city
0 2019-6-7 London is good. London
1 2019-5-8 I am going to Paris. Paris
2 2019-4-4 Do you want to go to London? London
3 2019-3-7 I love Paris! Paris注意,如果有多个匹配项,则extractall将返回一个列表
https://stackoverflow.com/questions/56944934
复制相似问题