Я хочу очистить столбец location
, удалив почтовые индексы, но я получаю следующую ошибку при извлечении и использовании регулярного выражения:
AttributeError: 'str' object has no attribute 'str'
Вот примерный фрейм данных только со столбцом местоположения :
In [52]: df
Out[52]:
location
0 New Feliciamouth, WA 16422
1 Bakerfurt, CO 76376
2 Lake Elizabethview, GA 59017
3 Robertschester, TX 92366
4 Robinsonmouth, AL 99445
5 North Connor, AZ 79552
6 Morganstad, WA 73506
7 New Roberto, IA 11832
8 Collierstad, DC 22151
9 Reneemouth, NJ 93901
(это данные, сгенерированные случайным образом для иллюстрации проблемы).
Я хочу, чтобы разные города выглядели так:
New Feliciamouth, WA
Bakerfurt, CO
et c.
Я использую этот код:
def get_city(address):
pattern = r'(.+\,\w.+)\w.+)'
return address.str.extract(pattern,flags=re.I)
location = df['location']
location.apply(get_city)
location.head()
Однако, я получаю исключение при запуске этого:
AttributeError Traceback (most recent call last)
<ipython-input-62-cdec695003fd> in <module>
4
5 location = df['location']
----> 6 location.apply(get_city)
7 location.head()
.../lib/python3.8/site-packages/pandas/core/series.py in apply(self, func, convert_dtype, args, **kwds)
4043 else:
4044 values = self.astype(object).values
-> 4045 mapped = lib.map_infer(values, f, convert=convert_dtype)
4046
4047 if len(mapped) and isinstance(mapped[0], Series):
pandas/_libs/lib.pyx in pandas._libs.lib.map_infer()
<ipython-input-62-cdec695003fd> in get_city(address)
1 def get_city(address):
2 pattern = r'(.+\,\w.+)\w.+)'
----> 3 return address.str.extract(pattern,flags=re.I)
4
5 location = df['location']
AttributeError: 'str' object has no attribute 'str'
Или при удалении .str перед извлекая я получаю:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-63-bfed6f810b40> in <module>
4
5 location = df['location']
----> 6 location.apply(get_city)
7 location.head()
.../lib/python3.8/site-packages/pandas/core/series.py in apply(self, func, convert_dtype, args, **kwds)
4043 else:
4044 values = self.astype(object).values
-> 4045 mapped = lib.map_infer(values, f, convert=convert_dtype)
4046
4047 if len(mapped) and isinstance(mapped[0], Series):
pandas/_libs/lib.pyx in pandas._libs.lib.map_infer()
<ipython-input-63-bfed6f810b40> in get_city(address)
1 def get_city(address):
2 pattern = r'(.+\,\w.+)\w.+)'
----> 3 return address.extract(pattern,flags=re.I)
4
5 location = df['location']
AttributeError: 'str' object has no attribute 'extract'