尝试使用Pandas计算百分比并添加新列

2024-06-16 12:57:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个使用groupby创建的pandas数据帧,返回的结果是:

          loan_type
type            
risky      23150
safe       99457

我想创建一个名为pct的列并将其添加到dataframe中我这样做了:

^{pr2}$

结果是:

       loan_type  pct
type                 
risky      23150  NaN
safe       99457  NaN

此时,我不确定我需要做些什么来获得百分比列,请参阅下面的代码,了解我是如何创建整个项目的:

import numpy as np
bad_loans = np.array(club['bad_loans'])

for index, row in enumerate(bad_loans):
    if row == 0:
        bad_loans[index] = 1
    else:
        bad_loans[index] = -1

loans = pd.DataFrame({'loan_type' : bad_loans})
loans['type'] = np.where(loans['loan_type'] == 1, 'safe', 'risky')loans = np.absolute(loans.groupby(['type']).agg({'loan_type': 'sum'}))
total = loans.sum(numeric_only=True)
loans['pct'] = loans.apply(lambda x:x/ total)

Tags: pandasindextypenpnansaferowtotal
1条回答
网友
1楼 · 发布于 2024-06-16 12:57:51

存在一个问题,您不想除以值,而是要除以一个值Series,因为没有对齐indexesgetNaNs

我认为最简单的方法是将Seriestotal转换成{}:

total = loans.sum(numeric_only=True)
loans['pct'] = loans.loan_type / total.values

print (loans)
       loan_type       pct
type                      
risky      23150  0.188815
safe       99457  0.811185

或通过索引转换选择[0]-输出为数字:

^{pr2}$

相关问题 更多 >