且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Seaborn和Pandas:使用python中的多索引数据制作多个x类别条形图

更新时间:2022-12-25 22:11:56

这就是您需要的找出该组每个数字的一​​部分:

This is what you need to find the portion of each number for that group:

df['proportion'] = df['value'] / df.groupby(['Color','variable'])['value'].transform('sum')

输出:

   variable              Frequency Color  value   portion
0         x      2-3 times a month   Red     22  0.052257
1         x      A few days a week   Red     45  0.106888
2         x    At least once a day   Red    344  0.817102
3         x                  Never   Red      5  0.011876
4         x           Once a month   Red      1  0.002375
5         x            Once a week   Red      0  0.000000
6         x  Once every few months   Red      4  0.009501
7         x      2-3 times a month  Blue      4  0.013605
8         x      A few days a week  Blue     49  0.166667
9         x    At least once a day  Blue    200  0.680272
10        x                  Never  Blue      7  0.023810
11        x           Once a month  Blue     19  0.064626
12        x            Once a week  Blue     10  0.034014
13        x  Once every few months  Blue      5  0.017007
14        y      2-3 times a month   Red      3  0.011905
15        y      A few days a week   Red     97  0.384921
16        y    At least once a day   Red    144  0.571429
17        y                  Never   Red      4  0.015873
18        y           Once a month   Red      0  0.000000
19        y            Once a week   Red      0  0.000000
20        y  Once every few months   Red      4  0.015873
21        y      2-3 times a month  Blue     44  0.099773
22        y      A few days a week  Blue     62  0.140590
23        y    At least once a day  Blue    300  0.680272
24        y                  Never  Blue      2  0.004535
25        y           Once a month  Blue      4  0.009070
26        y            Once a week  Blue     23  0.052154
27        y  Once every few months  Blue      6  0.013605
28        z      2-3 times a month   Red      4  0.031496
29        z      A few days a week   Red     12  0.094488
30        z    At least once a day   Red    101  0.795276
31        z                  Never   Red      0  0.000000
32        z           Once a month   Red      0  0.000000
33        z            Once a week   Red     10  0.078740
34        z  Once every few months   Red      0  0.000000
35        z      2-3 times a month  Blue    100  0.110375
36        z      A few days a week  Blue    203  0.224062
37        z    At least once a day  Blue    299  0.330022
38        z                  Never  Blue      0  0.000000
39        z           Once a month  Blue      0  0.000000
40        z            Once a week  Blue    204  0.225166
41        z  Once every few months  Blue    100  0.110375