mkoala mkoala - 1 year ago 99
Python Question

Accesing every 1st element of Pandas DataFrame column containing lists

I have a Pandas DataFrame with a column containing lists objects

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 Source

You can use map and a lambda function

df.loc[:, 'new_col'] = x: x[0])

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download