Home > Back-end >  How to extract last word from a column of a pandas dataframe
How to extract last word from a column of a pandas dataframe

Time:04-19

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

CodePudding user response:

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

CodePudding user response:

Use str.extract:

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