Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Last Word in a String within a List (Pandas, Python 3)

I have a DF named 'Stories" that looks like this:

Story
The Man
The Man Child
The Boy of Egypt
The Legend of Zelda

Is there a way to extract the last word in each of those strings?

Something like:

Stories['Prefix'] = final['Story'].str.extract(r'([^ ]*)') 

finds the prefix but I am not sure how to adapt it accordingly

I was hoping to end up with something like

Story                  Suffix
The Word Of Man         Man
The Man of Legend       Legend
The Boy of Egypt        Egypt
The Legend of Zelda     Zelda

Any help would be much appreciated!

like image 383
user3682157 Avatar asked Sep 17 '14 21:09

user3682157


People also ask

How do I extract the last word from a string in Python?

Take an empty string, newstring. Traverse the string in reverse order and add character to newstring using string concatenation. Break the loop till we get first space character. Reverse newstring and return it (it is the last word in the sentence).

What does last () do in Python?

The last() method returns the last n rows, based on the specified value. The index have to be dates for this method to work as expected.

How do you get the last value in a pandas series?

Pandas iloc is used to retrieve data by specifying its integer index. In python negative index starts from end therefore we can access the last element by specifying index to -1 instead of length-1 which will yield the same result.

How do I find the last 10 entries in pandas?

Use pandas. DataFrame. tail() to get the last n rows of a DataFrame.


1 Answers

You can use .str twice, as .str[-1] will pick up the last element:

>>> df["Suffix"] = df["Story"].str.split().str[-1]
>>> df
                 Story Suffix
0              The Man    Man
1        The Man Child  Child
2     The Boy of Egypt  Egypt
3  The Legend of Zelda  Zelda
like image 120
DSM Avatar answered Oct 24 '22 02:10

DSM