How to extract string with regex from a df using function and create new column?

Viewed 21

My dataframe

Description
a hello from 528-appname
another hellow 269-xyz-appname

Desired output

Description                            Application
a hello from 528-appname               appname
another hellow 269-xyz-appname         appname

What I tried

def generate_app_name(row):
    if '528-' in row['Description']:
        return row['Description'].str.contains(r'528-(\w+\w+)')
    if '269-xyz-' in row['Description']:
        return row['Description'].str.contains(r'269-xyz-(\w+\w+)')
    else:
        return('NA')

df['Application'] = df.apply(generate_app_name, axis=1)

Error

AttributeError: 'str' object has no attribute 'str'

528- and 269-xyz- never changes in description. app name is always in this format.

How can i achieve the desired result?

1 Answers

Use str.extract to handle a regex directly on the whole Series:

df['Application'] = df['Description'].str.extract(r'(?:528-|269-xyz-)(\w+\b)')

Output:

                      Description Application
0        a hello from 528-appname     appname
1  another hellow 269-xyz-appname     appname
Related