#python #pandas
#python #pandas
Вопрос:
У меня есть фрейм данных с информацией data1
, и я хотел бы добавить столбец, data2
содержащий только имена из data1
:
data1 data2
0 info name: Michael Jackson New York Michael Jackson
1 info 12 name: Michael Jordan III Los Angeles Michael Jordan III
Вы знаете, как я могу это сделать?
Ответ №1:
Без однозначного разделителя это нетривиально, поскольку у вас есть оба пробела внутри имен, имена нескольких длин (2 слова, 3 слова) и завершающий столбец, который также может содержать несколько слов с пробелами.
Разделив строку, вы можете достичь этого частичного решения:
df['data2'] = df['data1'].str.split(': ').str[-1]
>>> print(df)
data1 data2
0 info name: Michael Jackson New York Michael Jackson New York
1 info 12 name: Michael Jordan III Los Angeles Michael Jordan III Los Angeles
Если бы у вас был список «городов», вы могли бы выполнить полное решение:
def replace(string, substitutions):
"""Replaces multiple substrings in a string."""
substrings = sorted(substitutions, key=len, reverse=True)
regex = re.compile('|'.join(map(re.escape, substrings)))
return regex.sub(lambda match: substitutions[match.group(0)], string)
# List of cities to remove from strings
cities = ['New York', 'Los Angeles']
# Dictionary matching each city with the empty string
substitutions = {city:'' for city in cities}
# Splitting to create new column as above
df['data2'] = df['data1'].str.split(': ').str[-1]
# Applying replacements to new column
df['data2'] = df['data2'].map(lambda x: replace(x, substitutions).strip())
>>>print(df)
data1 data2
0 info name: Michael Jackson New York Michael Jackson
1 info 12 name: Michael Jordan III Los Angeles Michael Jordan III
Спасибо Карлсмиту за функцию замены.