coelidonum
coelidonum

Reputation: 543

Nested dictionary out of grouped pandas dataframe

I have a pandas dataframe like this:

    Tail Number | flight route | digit
    _______________
    001C     | (VB, MI)   | 1
             | (CC, SK)   | 2
             | (KF, KC)   | 1
    004N     | (AZ, AL)   | 2
             | (AU, NY)   | 3
    005F     | (ALB, TPA) | 5
             | (ORD, JAC) | 2

the variables that i'm interested in are tail number, fligh route (a tuple) and digit (which is an integer value column).

i would like to make a nested dictionary out of it having tail number as key and an other inner dictionary where the key is flight route and value is digit. The nested dictionary ideally would look like this:

d = {001C :{  {(VB, MI): 1}, {(CC, SK): 2},  {(KF, KC):1} },
    004N :{    {(AZ, AL): 2}, {(AU, NY):3},
    005F :{  {(ALB, TPA):5},  {(ORD, JAC):2},  ... }

could you help me?

Upvotes: 2

Views: 126

Answers (2)

Andy L.
Andy L.

Reputation: 25239

One way is using groupby and dict comprehension

{k: dict(zip(v['flight route'], v['digit'])) for k, v in df.groupby('Tail Number')}

Out[209]:
{'001C': {('VB', 'MI'): 1, ('CC', 'SK'): 2, ('KF', 'KC'): 1},
 '004N': {('AZ', 'AL'): 2, ('AU', 'NY'): 3},
 '005F': {('ALB', 'TPA'): 5, ('ORD', 'JAC'): 2}}

Upvotes: 1

Jim Eisenberg
Jim Eisenberg

Reputation: 1500

You can use a dict comprehension like this:

d = {i: {j:df.loc[(df['Tail Number']==i)&           
                  (df['flight route']==j),'digit'].iloc[0] #take every digit
           for j in df.loc[df['Tail Number']==i,'flight route']} #for every flight route
           for i in df['Tail Number']} #in each Tail Number

Two dict comprehensions which, like for loops, iterate over 1) Tail Number and 2) flight route (within each Tail Number).

Out[8]: 
{'001C': {('VB', 'MI'): 1, ('CC', 'SK'): 2, ('KF', 'CC'): 1},
 '004N': {('AZ', 'AL'): 2, ('AU', 'NY'): 3},
 '005F': {('ALB', 'TPA'): 5, ('ORD', 'JAC'): 2}}

If you have a multiindex you may need to first do

df = df.reset_index()

Upvotes: 1

Related Questions