user18734161
user18734161

Reputation: 53

How to extract last word from a column of a pandas dataframe

My pandas df column looks like this:-

Col1


Closed

Closed+Captives

Closed+Captives+Blank

Closed+Sync

Open

Open+Captives

Open+Captives+Blank

Open+Captives+Blank+Book

Open+Sync

Open+Sync+Candle


My output should be:-

Col1


Closed

Captives

Blank

Sync

Open

Captives

Blank

Book

Sync

Candle

I want this to be done using pandas. Please help me

Upvotes: 2

Views: 1494

Answers (2)

Abhyuday Vaish
Abhyuday Vaish

Reputation: 2379

Edit: After looking at your comment that there are + between words.

You can use .apply() and split each row by + to get the last word:

df['Col1'] = df['Col1'].apply(lambda x: x.split('+')[-1])

Output:

       Col1
0    Closed
1  Captives
2     Blank
3      Sync
4      Open
5  Captives
6     Blank
7      Book
8      Sync
9    Candle

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521279

Use str.extract:

df["Col1"] = df["Col1"].str.extract(r'(\w+)$')

Upvotes: 0

Related Questions