0

I have this code:

 new_dict = {'x':[1,2,3,4,5], 'y':[11,22,33,44,55], 'val':[100, 200, 300, 400, 500]}
df = pd.DataFrame.from_dict(new_dict)   
    val  x   y
0  100  1  11
1  200  2  22
2  300  3  33
3  400  4  44
4  500  5  55

I want to be able to use values of x and y in combination as index into val, for example

df[3][33]
300

What's the best way to achieve this? I know it must have to do with multi index, but I am not sure exactly how.

6
  • 1
    Sorry are you asking for df.loc[(df['x']==3) & (df['y']==33), 'val']? Commented Nov 11, 2015 at 16:38
  • That will indeed give the correct result, but I was wondering if there is more elegant, syntax-wise cleaner approach. Commented Nov 11, 2015 at 16:39
  • Well you don't have a multi-index here and besides what you're looking for are row value matches you're not using any index here Commented Nov 11, 2015 at 16:41
  • Thanks. But is it more practical to construct a multi-index, and then use that? Commented Nov 11, 2015 at 16:42
  • 1
    It depends but if you did set the index then you can do df.set_index(['x','y']).loc[3,33] which syntactically maybe easier for you Commented Nov 11, 2015 at 16:44

2 Answers 2

1

You can either define 2 boolean conditions as a mask and use with .loc:

df.loc[(df['x']==3) & (df['y']==33), 'val']

otherwise just set the index and then you can use those values to index into the df:

In [233]:
df = df.set_index(['x','y'])
df.loc[3,33]

Out[233]:
val    300
Name: (3, 33), dtype: int64

You could wrap the first version into a func quite easily

Sign up to request clarification or add additional context in comments.

Comments

1

You can define a function :

new_dict = {'x':[1,2,3,4,5], 'y':[11,22,33,44,55], 'val':[100, 200, 300, 400,   500]}

df = pd.DataFrame.from_dict(new_dict) 

def multindex(x,y):
    return df.set_index(['x','y']).loc[x,y]

multindex(1,11) #will return '100'

1 Comment

This seems pretty wasteful to construct a df with a multi-index for the purpose of returning a single element

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.