Python - Get Last Element After Str.Split()

Python - Get Last Element after str.split()

Use a list comprehension to take the last element of each of the split strings:

ids = [val[-1] for val in your_string.split()]

Get last column after .str.split() operation on column in pandas DataFrame

Do this:

In [43]: temp2.str[-1]
Out[43]:
0 p500
1 p600
2 p700
Name: ticker

So all together it would be:

>>> temp = pd.DataFrame({'ticker' : ['spx 5/25/2001 p500', 'spx 5/25/2001 p600', 'spx 5/25/2001 p700']})
>>> temp['ticker'].str.split(' ').str[-1]
0 p500
1 p600
2 p700
Name: ticker, dtype: object

Python splitting string and get last part

You can use rsplit:

s = "Chiuso\n\n\n\n\r\nPARTE ISCHIA PORTO"

s.rsplit("\n")[-1].capitalize()

Output:

'Parte ischia porto'

Last element in python list, created by splitting a string is empty

You have an empty string because the split on the last - character produces an empty string on the RHS. You can strip all '-' characters from the string before splitting:

wordlist = wordstring.strip('-').split('-')

partition string in python and get value of last segment after colon

result = mystring.rpartition(':')[2]

If you string does not have any :, the result will contain the original string.

An alternative that is supposed to be a little bit slower is:

result = mystring.split(':')[-1]

how to get second last and last value in a string after separator in python

Try this :

>>> s = "client_user_username_type_1234567"
>>> '_'.join(s.split('_')[-2:])
'type_1234567'

Split a List of Strings - to get first and last element

Using list comprehension

wind_direction=[(y.split(' '))[0] for y in wind]
print(wind_direction)

wind_strength=[int((x.split(' ')[2]).split('kph')[0]) for x in wind if x != '']
print(wind_strength)

Output

['', 'W', 'SSE', 'SSE', 'WSW', 'WSW', 'S', 'SW', 'NNW']
[6, 14, 23, 28, 15, 9, 18, 6]

Split pandas column and add last element to a new column

You need another str to access the last splits for every row, what you did was essentially try to index the series using a non-existent label:

In [31]:

df['lastname'] = df['fullname'].str.split().str[-1]
df
Out[31]:
fullname lastname
0 martin master master
1 andreas test test

Python: How to split and re-join first and last item in series of strings

You can use split and rsplit to get the various parts:

result = [f"{x.split(',', 1)[0]},{x.rsplit(',', 1)[1]}" if x.find(',') > 0 else x
for x in strings]

If strings is a pd.Series object then you can convert it back to a series:

result = pd.Series(result, index=strings.index)


Related Topics



Leave a reply



Submit