Populate a variable from print output in a loop

Viewed 55

I have a dataframe like the following:

df = pd.DataFrame(
    data=
    [['22 take away', 'something'],
     ['takeaway 56', 'I see'],
     ['45 takeaway street', ' This is blue'],
     ['right street', ' This is white']],
    columns=['V1', 'V2']
)

I want to extract the numbers from V1 to a separate variable in that dataframe using regex pattern. I have the following till now:

pattern =  r'\d{1,2}'
for i in df.V1:
    num = re.search(pattern, i)
    if num:
        print(num.group(0))

This prints out the numbers but my tries to separate these in a variable are all wrong till now. My goal is to have the following dataframe:

dfgoal = pd.DataFrame(
    data=
    [['22 take away', 'something', '22'],
     ['takeaway 56', 'I see', '56'],
     ['45 takeaway street', ' This is blue', '45'],
    ['right street', ' This is white', ' ']],
    columns=['V1', 'V2', 'V3']
)

Thanks very much!

1 Answers

Don't print but append value to some list and later assign this list to df["V3"]

And remeber to add empty string when it doesn't find num

import pandas as pd
import re

df = pd.DataFrame(
    data=[
        ['22 take away', 'something'],
        ['takeaway 56', 'I see'],
        ['45 takeaway street', ' This is blue'],
        ['right street', ' This is white']
    ],
    columns=['V1', 'V2']
)

# ------------

results = []

pattern =  r'\d{1,2}'

for i in df.V1:
    num = re.search(pattern, i)
    if num:
        #print(num.group(0))
        results.append(num.group(0))
    else:
        results.append("")
        
df['V3'] = results

# ------------

print(df)

Result:

                   V1              V2  V3
0        22 take away       something  22
1         takeaway 56           I see  56
2  45 takeaway street    This is blue  45
3        right street   This is white 

EDIT:

It is simpler to use .str.extract(pattern) (as @Barmar suggested in comment).

But pattern needs ( ) to capture value.

When it doesn't find number then it puts NaN and it needs .fillna("") to replace NaN with empty string.

pattern =  r'(\d{1,2})'
        
df['V3'] = df['V1'].str.extract(pattern).fillna("")
Related