对数据框进行排序并用百分比计算值 [英] Sort a Dataframe and count a value with percentages

查看:106
本文介绍了对数据框进行排序并用百分比计算值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的DataFrame:

I have a DataFrame like this:

Kind   Status
1      True
2      False
3      True
2      False
2      True

我用它计算了种类df.Kind.sort_values() 并得到了这个:

I counted the kinds with it df.Kind.sort_values() and got this:

1       1
2       3
3       1

现在我想看看种类2中有多少是真或假.像这样:

Now I want to see how much of Kind 2 are true or false as number and percent. Like this:

Art  True  False
  2     1      2
  2  0.33   0.66

有人可以帮助我吗? 最好的问候

Can someone help me? Best regards

推荐答案

crosstab + div

使用 pandas.crosstab :

res = pd.crosstab(df['Kind'], df['Status'])

res[['Pct False', 'Pct True']] = res.div(res.sum(axis=1), axis=0)

print(res)

Status  False  True  Pct False   Pct True
Kind                                     
1           0     1   0.000000   1.000000
2           2     1   0.666667   0.333333
3           0     1   0.000000   1.000000

我认为,这是显示数据的最自然的方法.不建议在单个系列中将计数与百分比相结合.

In my opinion, this is the most natural way to display your data. Combining counts with percentages in a single series is not recommended.

或者,您可以加入几个crosstab结果,一个归一化,另一个不归一.

Alternatively, you can join a couple of crosstab results, one normalized, the other not.

res = pd.crosstab(df['Kind'], df['Status'])\
        .join(pd.crosstab(df['Kind'], df['Status'], normalize='index'), rsuffix='_pct')

print(res)

Status  False  True  False_pct  True_pct
Kind                                    
1           0     1   0.000000  1.000000
2           2     1   0.666667  0.333333
3           0     1   0.000000  1.000000

交叉表仅规范化

如果只寻找百分比,则可以使用normalize参数:

res = pd.crosstab(df['Kind'], df['Status'], normalize='index')

print(res)

Status     False     True 
Kind                      
1       0.000000  1.000000
2       0.666667  0.333333
3       0.000000  1.000000

这篇关于对数据框进行排序并用百分比计算值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆