Baron Yugovich
Baron Yugovich

Reputation: 4315

MultiIndex for pandas dataframe

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.

Upvotes: 0

Views: 77

Answers (2)

EdChum
EdChum

Reputation: 394459

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

Upvotes: 1

Mir Ilias
Mir Ilias

Reputation: 515

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'

Upvotes: 1

Related Questions