1

I want to take a slice of a pivot table from a dataframe with a search parameter. My pivot table looks like this.

Catbot ID      23146                      ...     27496                    
Catbot Class 1       2       3  ...       1       2       3
Temp                                ...                              
-40   1.034186  1.913528  1.201873  ...  0.970529  0.655468  0.757292
-20   1.477101  2.345765  1.210887  ...  1.131868  0.893106  2.054562
 0    1.830920  2.859917  2.509851  ...  1.530676  1.484927  1.714086
 25   2.054562  1.950517  2.720870  ...  1.712430  2.055812  1.596281
 50   2.503126  3.136164  1.927240  ...  1.347517  1.870755  2.338643
 85   1.818063  2.043732  2.113338  ...  1.970478  1.649569  1.508415
 110  2.077481  1.770812  2.144629  ...  1.668171  1.603300  1.566150

To get a slice of this pivot table by the Catbot ID, I do this.

catids = list(pivotTable.columns.levels[0])   # get list of IDs
catid = catids[1]   # get first ID
slice = pivotTable.loc[:,catid]   # get slice. 

My slice then looks like this.

Catbot Class 1       2       3
Temp                              
-40   1.034186  1.913528  1.201873
-20   1.477101  2.345765  1.210887
 0    1.830920  2.859917  2.509851
 25   2.054562  1.950517  2.720870
 50   2.503126  3.136164  1.927240
 85   1.818063  2.043732  2.113338
 110  2.077481  1.770812  2.144629

But it's missing the catid.

How do would one go about restoring the search parameter used to get the slice? In other words, how can I get my slice to look like this.

Catbot ID     23146
Catbot Class 1       2       3
Temp                              
-40   1.034186  1.913528  1.201873
-20   1.477101  2.345765  1.210887
 0    1.830920  2.859917  2.509851
 25   2.054562  1.950517  2.720870
 50   2.503126  3.136164  1.927240
 85   1.818063  2.043732  2.113338
 110  2.077481  1.770812  2.144629

Thank you.

S. Worley
  • 21
  • 7
  • Use `pd.IndexSlice` to slice a MultiIndex: `df.loc[:, pd.IndexSlice[catid, :]]` Columns are covered in the "Bonus Question" section, but really everything about rows is applicable – ALollz Jul 23 '19 at 15:54
  • I think you just need to wrap your catId into a list, like this `slice = pivotTable.loc[:,[catid]]`. – jottbe Jul 23 '19 at 16:00
  • @ALollz that worked perfectly, thank you. – S. Worley Jul 23 '19 at 16:04

0 Answers0