python - 将列值四舍五入到最接近的 10,然后显示满足条件的每个组的百分比
问题描述
df = pd.DataFrame({'Credit Scores':[695 ,704, 718], 'Delinquent': [True, False, True]})
df.head()
初学者使用 pandas 数据帧
所以我创建了一个数据框,其中包括借款人在贷款发起时的信用评分以及贷款是否拖欠。我希望通过将分数四舍五入太接近 10 来将分数组合在一起(即“信用分数”:700、710、720 等),然后找出每组中拖欠分数的百分比。示例输出可能如下所示。
Credit Score Delinquency Rate
0 700 .43
1 710 .45
2 720 .41
我不确定如何做到这一点,非常感谢一些指导。谢谢
更新
我遇到了另一个问题
#round and group credit scores by 10's
df['Credit Score'] = round(df['Credit Score'], -1)
# group by credit score and sum the bool values divided by the size of each group
to_rate = df.groupby(round(df['Credit Score'], -1))['Delinquency Rate']
df['Delinquency Rate'] = to_rate.transform(sum) / to_rate.transform('size')
df.sort_values('Credit Score')
因此,当我对值进行排序和显示时,我注意到信用评分正在重复。我似乎没有正确地将它们分组...
Credit Score Delinquency Rate
54 450 1.0
17 470 0.0
28 470 0.0
10 480 0.5
59 480 0.5
我应该如何解决这个问题?还有一种方法可以显示多于小数位吗?
更新的输出
我删除了这段代码以避免规范化,但现在它没有对值进行四舍五入。
df['Credit Score'] = round(df['Credit Score'], -1)
删除上面的行后的新输出
df.sort_values('Credit Score')
Credit Score Delinquency Rate
54 447 1.0
28 471 0.0
17 474 0.0
21 475 0.5
10 476 0.5
... ... ...
16 839 0.0
28 839 0.0
45 839 0.0
65 839 0.0
62 839 0.0
解决方案
IIUC
# new sample df
df = pd.DataFrame({'Credit Scores':[654 ,738, 863, 649, 650],
'Delinquent': [True, False, True, True, False]})
# use round with -1 to round to the nearest 10
df['Credit Scores'] = round(df['Credit Scores'], -1)
# group by credit score and get the mean
s = df.groupby('Credit Scores')['Delinquent'].mean()
s.reset_index().plot(kind='scatter', x='Credit Scores', y='Delinquent')
Delinquent
Credit Scores
650 0.666667
740 0.000000
860 1.000000
推荐阅读
- ios - 如何在没有空间问题的情况下创建各种大小的 collectionView 单元格
- javascript - 在reactjs中上传之前的多重图像预览?
- java - 如何在 Selenium Java 中转换 Katalon 脚本?
- angular - 在子组件中测试发出的值
- python-3.x - 自动从网站下载某些 csv 文件
- karate - com.intuit.karate.exception.KarateException: user.feature:11 - 找不到步骤定义方法匹配:匹配响应
- database - PostgreSQL:PgAdmin 上具有 3 个主键的表的外键
- python-3.x - 在 Python 的 for 循环中未激活 Break
- flutter - 如何在 TextField() Flutter 上设置范围数值
- c# - 在 Castle Windsor 中注册泛型接口的多个实现