cosmosa
cosmosa

Reputation: 761

pandas: reshape dataframe for stacked bar plot

I have a dataframe like this

          meaning           label  \
0         hypertension      0   
1         angina            5   
2         angina            9   
  percentFeatureInCluster  percentFeatureInPop  
0               33.781654            30.618880  
1               24.916958             3.768201  
2                4.663107             3.768201 

I am trying to group by meaning, and get a stacked bar plot where there are as many bars per meaning as there are rows in each group + an additional one for percentFeatureInPop.

I.e this would be the DataFrame I am looking for, which I can easily feed into plot.bar(stacked=True) and get the plot I'm looking for.

     meaning  percentFeatureInCluster0   percentFeatureInCluster5 
hypertension                 33.781654                          0
angina                               0                  24.916958

percentFeatureInCluster9     percentFeatureInPop
                       0               30.618880
                4.663107                3.768201  

How can this be achieved?

Upvotes: 1

Views: 117

Answers (1)

piRSquared
piRSquared

Reputation: 294198

pre = 'percentFeatureInCluster'
d1 = df.set_index(['meaning', 'label'])[pre].unstack(fill_value=0).add_prefix(pre)
d1.plot.bar(stacked=True, figsize=[10, 4])

enter image description here

Upvotes: 1

Related Questions