【问题标题】:pandas: reshape dataframe for stacked bar plotpandas:为堆积条形图重塑数据框
【发布时间】:2017-04-26 04:51:27
【问题描述】:

我有一个这样的数据框

          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 

我正在尝试按含义进行分组,并获得一个堆积条形图,其中每个含义的条形与每个组中的行数一样多,另外还有一个用于 percentFeatureInPop。

也就是说,这将是我正在寻找的 DataFrame,我可以轻松地将其输入 plot.bar(stacked=True) 并获得我正在寻找的情节。

     meaning  percentFeatureInCluster0   percentFeatureInCluster5 
hypertension                 33.781654                          0
angina                               0                  24.916958

percentFeatureInCluster9     percentFeatureInPop
                       0               30.618880
                4.663107                3.768201  

如何做到这一点?

【问题讨论】:

    标签: pandas matplotlib


    【解决方案1】:
    pre = 'percentFeatureInCluster'
    d1 = df.set_index(['meaning', 'label'])[pre].unstack(fill_value=0).add_prefix(pre)
    d1.plot.bar(stacked=True, figsize=[10, 4])
    

    【讨论】:

    • @cosmos1990 很高兴我能帮上忙
    猜你喜欢
    • 2018-09-28
    • 1970-01-01
    • 2014-11-14
    • 2016-05-24
    • 2018-05-09
    • 1970-01-01
    相关资源
    最近更新 更多