Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python pandas: access the element of the list in DataFrame

Tags:

python

pandas

i have a problem with accessing list element in 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}})

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

I think it would be smth like this:

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

but instead x[0] i need x[d.n].

I read manual and search the forum but havn't found anything. I fill it smth obvious, but i stucked. Help me, please.

like image 740
user3661347 Avatar asked May 21 '14 15:05

user3661347


People also ask

How do you access a specific element in a DataFrame?

By using at and iat attributes We can also access a single value of a DataFrame with the help of “at” and “iat” attributes. Access a single value by row/column name. At and iat take two arguments. If we pass only one argument, then it will generate an error.

How do you access a DataFrame list in Python?

Using Series.tolist() From the dataframe, we select the column “Name” using a [] operator that returns a Series object. Next, we will use the function Series. to_list() provided by the Series class to convert the series object and return a list.

How do you access the elements of a series in pandas?

Accessing Element from Series with PositionUse the index operator [ ] to access an element in a series. The index must be an integer. In order to access multiple elements from a series, we use Slice operation.

Can pandas DataFrame hold a list?

Conclusion. By using df.at() , df. iat() , df. loc[] method you can insert a list of values into a pandas DataFrame cell.


1 Answers

Thanks to all! This works fine:

def func(x): 
    return x.pos[int(x.n)]

d['new column']=d.apply(lambda row: func(row), axis=1)
like image 169
user3661347 Avatar answered Oct 02 '22 07:10

user3661347