How to Access Element of Pandas Series that is a List

Viewed 3716

I have a Dataframe series that contains is a list of strings for each row. I'd like to create another series that is the last string in the list for that row.

So one row may have a list e.g

['a', 'b', 'c', 'd']

I'd like to create another pandas series made up of the last element of the row, normally access as a -1 reference, in this 'd'. The lists for each observation (i.e. row) are of varying length. How can this be done?

2 Answers

I believe need indexing with str, it working with all iterables:

df = pd.DataFrame({'col':[['a', 'b', 'c', 'd'],['a', 'b'],['a'], []]})

df['last'] = df['col'].str[-1]
print (df)
            col last
0  [a, b, c, d]    d
1        [a, b]    b
2           [a]    a
3            []  NaN

strings are iterables too:

df = pd.DataFrame({'col':['abcd','ab','a', '']})
df['last'] = df['col'].str[-1]
print (df)
    col last
0  abcd    d
1    ab    b
2     a    a
3        NaN

Why not making the list column to a info dataframe, and you can using the index for join

Infodf=pd.DataFrame(df.col.values.tolist(),index=df.index)
Infodf
Out[494]: 
      0     1     2     3
0     a     b     c     d
1     a     b  None  None
2     a  None  None  None
3  None  None  None  None

I think I over looked the question , and both PiR and Jez provided their valuable suggestion to help me achieve the final result .

Infodf.ffill(1).iloc[:,-1]
Related