Dataframe Split Text into new column

Viewed 45

I have a dataframe awith the following column MENU_HINT and im looking to make a new column by picking out the third word:

MENU_HINT
AUS / Cant (AUS) 
AUS / Darw (AUS)
AUS / YarV (AUS)
AUS / Goul (AUS)

My code is the following:

splittext = str(dfresults['MENU_HINT'])
dfresults['City'] = splittext.split()[3]

Which Gives Me:

MENU_HINT                City
AUS / Cant (AUS)         Cant
AUS / Darw (AUS)         Cant
AUS / YarV (AUS)         Cant
AUS / Goul (AUS)         Cant

I'm after Cant, Darw, YarV, Goul but it is fixing on the top value (Cant).

I know I'm close but cant seem to figure out the issue so any help would be great!

2 Answers

Use Series.str.split with slicing:

#fourth value
dfresults['City'] = dfresults['MENU_HINT'].str.split().str[3]

#third value
dfresults['City'] = dfresults['MENU_HINT'].str.split().str[2]

Another solution is to use pandas.Series.str.extract with regex:

df['City'] = df['MENU_HINT'].str.extract(r'/\s(\w+)')
print(df)

           MENU_HINT  City
0  AUS / Cant (AUS)   Cant
1   AUS / Darw (AUS)  Darw
2   AUS / YarV (AUS)  YarV
3   AUS / Goul (AUS)  Goul

This assumes the text to match is followed by '/' and could be at any position.

Related