mkoala mkoala - 3 months ago 9
Python Question

Accesing every 1st element of Pandas DataFrame column containing lists

I have a Pandas DataFrame with a column containing lists objects

A
0 [1,2]
1 [3,4]
2 [8,9]
3 [2,6]


How can I access the first Element of each list and save it into a new column of the DataFrame? To get a result like this

A new_col
0 [1,2] 1
1 [3,4] 3
2 [8,9] 8
3 [2,6] 2


I know this could be done via iterating over each row, but is there any "pythonic" way?

dmb dmb
Answer

You can use map and a lambda function

df.loc[:, 'new_col'] = df.A.map(lambda x: x[0])