archingfork
archingfork

Reputation: 155

How to strip everything from a row value except the first instance of an int?

If I have a row value as such:

Blow Balloons 5 Yes 4
3 Shirt No 
Goodbye Something 2 1

Then I just want it to be:

5
3
2

So the first instance of an int. How can I do that? I can't use a regex because there's no pattern for when the number first appears.

Upvotes: 0

Views: 146

Answers (2)

GConelhero
GConelhero

Reputation: 146

import re

list = ['Blow Balloons 5 Yes 4', 
    '3 Shirt No', 
    'Goodbye Something 2 1']

regex = re.compile("(\d){1}")

for str in list:
    data = regex.search(str).group()
    print(data)

Output:

5
3
2

Upvotes: 0

Y.P
Y.P

Reputation: 355

Here's a possible solution. It actually use regex :

import pandas as pd
data = ['Blow Balloons 5 Yes 4', 
        '3 Shirt No', 
        'Goodbye Something 2 1']
data = pd.Series(data)
data = data.str.replace(r'\D+', ' ').str.split()
data = data.apply(lambda x: x[0])

Upvotes: 1

Related Questions