#python #pandas #dataframe
Вопрос:
Я пытаюсь найти наибольшее число из строки в одном столбце из фрейма данных pandas, а затем создать другой столбец на основе максимального результата.
Мой Фрейм данных:
number_quotes
0 I have 1-50 ice-creams
1 4 people out of 10 said hello
2 8889 or 9500 but could be 10903
Желаемый результат:
number_quotes max_number
0 I have 1-50 ice-creams 50
1 4 people out of 10 said hello 10
2 8889 or 9500 but could be 10903 10903
Ответ №1:
Используйте Series.str.extractall
для всех чисел, преобразуйте в целые числа и в последний раз получите максимальные значения:
df['max_number'] = df['number_quotes'].str.extractall('(d )')[0].astype(int).max(level=0)
print (df)
number_quotes max_number
0 I have 1-50 ice-creams 50
1 4 people out of 10 said hello 10
2 8889 or 9500 but could be 10903 10903
Комментарии:
1. Это сработало идеально, спасибо вам за помощь.
Ответ №2:
Попробуйте с str.findall
:
>>> df['max_number'] = df['number_quotes'].str.findall('[0-9] ').apply(lambda x: max(map(int, x)))
>>> df
number_quotes max_number
0 I have 0-50 ice-creams 50
1 4 people out of 10 said hello 10
2 8889 or 9500 but could be 10903 10903
>>>