6

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.

7
  • 1
    Your code generates an empty dataframe, can you fix your dataframe construction code, thanks. Commented May 21, 2014 at 15:43
  • If I understand you correctly you better init you dataframe the following way d=DataFrame([{'pos': {0: [0.11,0.14,0.46]},'n': {0: 2.0}}, {'pos': {1: [0.1,0.4,0.6]},'n': {1: 1.0}}]) Commented May 21, 2014 at 15:49
  • Are you using python 2 or 3 as this will determine how to access the first value in the dict, also storin a dict with value as a list is painfully horrible Commented May 21, 2014 at 16:01
  • If using python 3 then using the dataframe construction code from Tom Ron then this works: def func(x): return next(iter(x.pos.values()))[int(next(iter(x.n.values())))] d['new column']=d.apply(lambda row: func(row), axis=1) Commented May 21, 2014 at 16:02
  • have fixed DataFrame. Sorry, it was the end of long day. Commented May 21, 2014 at 18:42

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.