首页 > 解决方案 > 将列值四舍五入到最接近的 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

标签: pythonpandasdataframedata-sciencerounding

解决方案


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

推荐阅读