Pandas: Finding the greatest number in a string from each field in a single column

Viewed 81

I'm trying to find a greatest number from a string in a single column from a pandas dataframe and then create another column based on the max result.

My Dataframe:

   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

Desired outcome:

   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
2 Answers

Use Series.str.extractall for all numbers, convert to integers and last get maximals:

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

Try with 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
>>> 
Related