【问题标题】:Unstack a MultiIndex pandas DataFrame counter-clockwise instead of clockwise逆时针而不是顺时针取消堆叠 MultiIndex pandas DataFrame
【发布时间】:2015-06-28 16:32:36
【问题描述】:

我有一个看起来像这样的多索引 pandas DataFrame:

                      Number of Vulnerabilities
Name       Severity
           moderate   2167
Person 1   high       1421
           critical   2464
           moderate   5841
Person 2   high       3687
           critical   10267

我的目标是创建一个带有条形的水平堆叠条形图,代表严重程度,从左到右依次为:中等、高、关键。为了获得堆叠条形图,我似乎需要取消堆叠严重性索引列。当我尝试这样做时,像这样,df.unstack('Severity'),我的 DataFrame 看起来像这样:

           Number of Vulnerabilities
Severity   critical  high  moderate
Name
Person 1   2464      1421  2167
Person 2   10267     3687  5841

所以,当我去绘制它时,堆叠的条形图是按顺序排列的 (L->R):关键、高、中等。
未堆叠时如何将“严重性”指数的顺序更改为:中等、高、关键?或者,有没有办法在绘图的时候改变顺序,免去对DataFrame进一步操作?
我当前的情节代码是df.plot(kind='barh', stacked=True)

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    您可以重新排列您的列。

    df = df.unstack('Severity') # This is your current dataframe
    
    df = df['Number of Vulnerabilities'][['moderate', 'high', 'critical']] # reoder
    df.plot(kind='barh', stacked=True) #plot
    

    【讨论】:

    • 行得通!但是,“漏洞数量”列名称已消失。有没有办法通过重新排序来保持它?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-29
    • 1970-01-01
    • 2012-12-11
    • 2019-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多