Quantcast
Viewing all articles
Browse latest Browse all 4

Answer by Allen Qin for pandas - create key value pair from grouped by data frame

#A to_dict() solutiond = df.groupby(['Col X','Col Y']).sum().reset_index().pivot(columns='Col X',values='Sum').to_dict()Out[70]: {'A': {0: 3.0, 1: 2.0, 2: 1.0, 3: nan, 4: nan, 5: nan},'B': {0: nan, 1: nan, 2: nan, 3: 5.0, 4: 6.0, 5: 7.0}}#if you need to get rid of the nans:{k1:{k2:v2 for k2,v2 in v1.items() if pd.notnull(v2)} for k1,v1 in d.items()}Out[73]: {'A': {0: 3.0, 1: 2.0, 2: 1.0}, 'B': {3: 5.0, 4: 6.0, 5: 7.0}}

Viewing all articles
Browse latest Browse all 4

Trending Articles