Is it possible to have multiple indexes into a pandas dataframe?

Viewed 623

Is it possible to have multiple indexes at once for a single pandas DataFrame?

By index I mean something close to what SQL databases or MongoDB would have to drastically increase the performance of some queries.

Imagine you have a dataframe of orders, and sometimes you would like to index into an order by its ID, and another time by indexing into an order by another key, say warehouse, client ID, time, something like that.

1 Answers

Short Answer : Yes.

Please refer https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html

s = pd.Series([1, 2, 3, 4])
df.set_index([s, s**2])
      month  year  sale
1 1       1  2012    55
2 4       4  2014    40
3 9       7  2013    84
4 16     10  2014    31

Another example for multiple index:

dct = {'id' : (0,0,1,1,2,2,3,3,4,4,5,5),
    'Store': ('A','A','A','A','A','A','B','B','B','C','C','C'),
       'code_num':('INC101','INC102','INC103','INC104','INC105','INC106','INC201','INC202','INC203','INC301','INC302','INC303'),
       'days':('4','18','9','15','3','6','10','5','3','1','8','5'),
       'products': ('remote','antenna','remote,antenna','TV','display','TV','display,touchpad','speaker','Cell','display','speaker','antenna')
}
df = pd.DataFrame(dct)
df.set_index(['id','Store','code_num'])

df :

enter image description here

Related