【问题标题】:Can't plot value counts for pie chart无法绘制饼图的值计数
【发布时间】:2016-08-26 02:24:28
【问题描述】:

我写了一个函数来绘制饼图中变量值的分布,如下所示。

def draw_piecharts(df, variables, n_rows, n_cols):
     df[variables].value_counts.plot(kind='pie', layout=(n_rows,n_cols), subplots=True)
     plt.show()
def main():
    util.draw_piecharts(df, [ 'TARGET', 'BanruptcyInd'], 1,2)
if __name__ == "__main__":
    main()

不幸的是,我的函数无法计算,因为数据框没有属性 value_counts(),而 value_counts 是我知道如何在饼图中绘制分布的唯一方法。 这是正在绘制的变量的示例:

0     0
1     0
2     0
3     0
4     0
5     0
6     0
7     0
8     0
9     0
10    0
11    0
12    1
13    0
14    0
15    0
16    0
17    1
18    0
19    0
20    0
21    1
22    0
23    0
24    1
25    0
26    1
27    0
28    0
29    0
Name: TARGET, dtype: int64
0     0
1     0
2     0
3     0
4     0
5     0
6     0
7     0
8     0
9     0
10    0
11    0
12    0
13    0
14    0
15    0
16    0
17    0
18    0
19    0
20    0
21    0
22    0
23    0
24    0
25    0
26    0
27    0
28    0
29    0

【问题讨论】:

    标签: python pandas dataframe pie-chart subplot


    【解决方案1】:

    虽然value_counts 是一个Series 方法,但它很容易通过使用DataFrame.apply 应用于DataFrames 中的Series。在你的情况下。例如,

    df[variables].apply(pd.value_counts).plot(kind='pie', layout=(n_rows,n_cols), subplots=True)
    

    (假设pandas 已导入为pd)。

    举个完整的例子:

    import pandas as pd
    a = pd.DataFrame({'a': [1,0,0,0,1,1,0,0,1,0,1,1,1],'b': [1,0,0,0,1,1,0,0,1,0,0,0,0]})
    a.apply(pd.value_counts).plot.pie(subplots=True)
    

    【讨论】:

      猜你喜欢
      • 2018-12-27
      • 2014-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多