从第四个逗号开始检索字符串
Retreive the string from the fourth comma
我有一个数据框,其中一列包含地址,我想从字符串中检索城市。例如,我想从下面检索翁布里亚。 (城市名称在第 4 个逗号之后)
Strada statale 71 Umbro Casentinese, Case Lunghe, Città della Pieve, Perugia, Umbria, 06062, Italia'
我试过在下面找到但只有 return 索引
a = 'Strada statale 71 Umbro Casentinese, Case Lunghe, Città della Pieve, Perugia, Umbria, 06062, Italia'
a.find(','4)
return : 35
不知道 pandas
(我假设您正在使用)是否有任何内置功能。
如果是这样,那就更好了,因为它比您将要编写的任何 python 代码都快得多。
但这是如何在纯 python:
def get_chunk(text, split_str = ",", pos = 4):
# split the string into chunks (frags) #
text = text.split(split_str)
# assuming all your addresses use the same format, this'll get you the City #
return text[pos]
get_chunk(a) # output: Umbria
或者你可以只做一个简单的一行而不是整个函数:
city = a.split(',')[4]
我有一个数据框,其中一列包含地址,我想从字符串中检索城市。例如,我想从下面检索翁布里亚。 (城市名称在第 4 个逗号之后)
Strada statale 71 Umbro Casentinese, Case Lunghe, Città della Pieve, Perugia, Umbria, 06062, Italia'
我试过在下面找到但只有 return 索引
a = 'Strada statale 71 Umbro Casentinese, Case Lunghe, Città della Pieve, Perugia, Umbria, 06062, Italia'
a.find(','4)
return : 35
不知道 pandas
(我假设您正在使用)是否有任何内置功能。
如果是这样,那就更好了,因为它比您将要编写的任何 python 代码都快得多。
但这是如何在纯 python:
def get_chunk(text, split_str = ",", pos = 4):
# split the string into chunks (frags) #
text = text.split(split_str)
# assuming all your addresses use the same format, this'll get you the City #
return text[pos]
get_chunk(a) # output: Umbria
或者你可以只做一个简单的一行而不是整个函数:
city = a.split(',')[4]