Python - Get Last Element after str.split()

28,974

Solution 1

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

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

Solution 2

Try the below solution:

item["x"]["y"].split(' ')[-1]

Solution 3

I thought I would add this simple solution which doesn't use lists or list comprehension to split an existing column/series and store the last item from the split to a new column/series in the DataFrame

import pandas as pd

data = ['FirstName LastName StudentID',
'FirstName2 LastName2 StudentID2']

df = pd.DataFrame(data=data, columns=['text'])

df['id'] = df.text.str.split(" ").str.get(-1)

Output:

index text id

0 FirstName LastName StudentID StudentID

0 FirstName2 LastName2 StudentID2 StudentID2

Solution 4

You could do something like this:

import pandas as pd

data = ['FirstName LastName StudentID',
'FirstName2 LastName2 StudentID2']

df = pd.DataFrame(data=data, columns=['text'])

df['id'] = df.text.apply(lambda x: x.split()[-1])

print(df)

Output

text          id
0     FirstName LastName StudentID   StudentID
1  FirstName2 LastName2 StudentID2  StudentID2

Or, as an alternative:

df['id'] = [x.split()[-1] for x in df.text]
print(df)

Output

text          id
0     FirstName LastName StudentID   StudentID
1  FirstName2 LastName2 StudentID2  StudentID2

Solution 5

Using data frame constructor

pd.DataFrame(df.text.str.split(' ').tolist()).iloc[:,0]
Out[15]: 
0     FirstName
1    FirstName2
Name: 0, dtype: object
Share:
28,974
Cayza Angka Maulana
Author by

Cayza Angka Maulana

Updated on September 05, 2021

Comments

  • Cayza Angka Maulana
    Cayza Angka Maulana over 2 years

    I use pandas and I have data and the data look like this

    FirstName LastName StudentID
    FirstName2 LastName2 StudentID2
    

    Then I split it based on 'space' using str.split()

    So the data will look like this in DataFrame

    [[FirstName, LastName, StudentID],
    [FirstName2, LastName2, StudentID2]]
    

    How to take the StudentID for every students only and save it in new column?

  • xkcdjerry
    xkcdjerry about 4 years
    Or you can use ids=[val[1] for val in your_string.rsplit(maxsplit=1)] It may be faster. :)