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!
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).
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.
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.
Use pandas. DataFrame. tail() to get the last n rows of a DataFrame.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With