Python pandas: access a list item in a DataFrame

I have a problem accessing a list item in a DataFrame:

import pandas as pd from pandas import DataFrame d=DataFrame({'pos': {0: [0.11,0.14,0.46], 1:[1,2,3]},'n': {0: 2.0,1:1}}) 

The 'pos' column contains a list. I need to compute a new column with the 'n'th element of the list in the pos'-column column. In this case: 0.46, 2.

I think it would be like this:

 d[u'new column']=d.pos.apply(lambda x: x[0]) 

but instead, x [0] I need x [dn].

I read the manual and searched the forum, but found nothing. I filled it with the obvious, but I was stuck. Help me please.

+6
source share
1 answer

Thanks everyone! This works great:

 def func(x): return x.pos[int(xn)] d['new column']=d.apply(lambda row: func(row), axis=1) 
+2
source

Source: https://habr.com/ru/post/969650/


All Articles