Copying a section of a string from one column and putting it into a new pandas column

Viewed 201

I'm cleaning a dataset and need to take the part of the string between the underscores (_). Column A is what I am starting with.

A   
foo_bar_foo
bar_foo_bar
bar
foo_bar_foo

I need to copy over the characters in between the underscores and copy them into a new column. Column B is the anticipated results.

A               B
foo_bar_foo     bar
bar_foo_bar     foo
bar             null
foo_bar_foo     bar

Any advice is appreciated.

2 Answers

Use str.split and .str[index]

df['B']=df.A.str.split('_').str[1]



      A        B
0  foo_bar_foo  bar
1  bar_foo_bar  foo
2          bar  NaN
3  foo_bar_foo  bar

Use extract:

df['B'] = df['A'].str.extract('_(\w+)_')
print(df)

Output

             A    B
0  foo_bar_foo  bar
1  bar_foo_bar  foo
2          bar  NaN
3  foo_bar_foo  bar
Related