简体   繁体   中英

Convert pandas pivot table with multiindex into nested dictionary

I looked through the various answers similar to my question, but could not find a solution for my specific case.

I am creating a pandas pivot table with a multiindex as such:

df = pd.pivot_table(df, index  = ['clusterKey',
                                 'campaignTitle',
                                 'couponName'],
                        values = ['salesValue','budgetSpent'])

and I'd like to create a data structure where the indexes are converted into a nested dictionary, so it becomes possible to access the datastructure like this:

val = dict['clusterKeyA']['campaignTitleB']['couponNameC']['salesValue']

Not sure if you are ok with this format but you can directly use pd.DataFrame.to_dict() , which is very easy and short. Then, you can access value using double nested dictionary, where the first level is a tuple of your three indices.

d = pt.to_dict("index")
d
{('A', 'a', 'd'): {'val1': 1.5, 'val2': 1.0},
 ('A', 'b', 'a'): {'val1': 3.0, 'val2': 4.0},
 ('B', 'a', 'a'): {'val1': 4.0, 'val2': 4.0},
 ('B', 'b', 'c'): {'val1': 5.0, 'val2': 1.0},
 ('B', 'c', 'c'): {'val1': 6.0, 'val2': 1.0},
 ('C', 'b', 'a'): {'val1': 7.0, 'val2': 3.0},
 ('C', 'b', 'b'): {'val1': 8.0, 'val2': 3.0},
 ('C', 'c', 'c'): {'val1': 9.0, 'val2': 1.0},
 ('C', 'c', 'd'): {'val1': 1.0, 'val2': 1.0}}

d[("A","a","d")]["val1"]
1.5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM