Skip to main content
 首页 » 编程设计

python之访问groupby的列

2024年11月01日14yxwkf

我有一个看起来像这样的表:

 Bank        Our Credit Rating      External Credit Rating       Deviation 
 A             11                      12                          1 
 D             10                      8                           2 
 A             4                       4                           0 
 B             6                       7                           1 
 C             12                      11                          1 
 A             9                       10                          1 

要提取所有偏差总和 >=50 的银行。我已经通过上面给出的代码做了同样的事情。

输出:

   [IN] 
   workbbok = pd.read_csv("Credit_Rating_comparison.csv") 
   df33= workbook.groupby('Bank').aggregate({"Deviation":np.sum}) 
   df44=df33[df33['Deviation']>=50] 
   [OUT] 
    Bank                                      Deviation                                   
    B                                          68.0 
    A                                          72.0 
 
    and so on for the relevant banks. (Basically sum of all deviations for  
    one bank where sum of all deviations is at least 50) 

我无法访问第 1 列,即 df44 中所有银行的名称。

    [IN]: df44.columns 
    [OUT]: Index(['Deviation'], dtype='object') 
    [IN]: df44.iloc[:,0] 
    [OUT] 
     Bank                                       
     B                                          68.0 
     A                                          72.0 
     #Using df44.iloc[:,0] doesnt give column name deviation also and  
     returns deviation results along with Bank name.  I want only bank names list.  

基本上我需要一个仅包含银行名称的列表(没有偏差总和),以便我可以进一步使用该列表进行以下操作。

在获得所有银行的名称后,我需要找到偏差列的频率分布。

下面的代码给出了所有行对应的频点。我想仅提取银行名称在 df44['Bank'] 中的行。任何帮助将不胜感激。

     [IN]: 
     bins = [0, 1,2,3,4,5] 
     workbook['Deviation Bins'] = pd.cut(workbook['Deviation'], bins,  
     include_lowest =True) 
     workbook  
     [OUT]: 
 Bank   Our Credit Rating  External Credit Rating Deviation  Deviation Bins 
 A             11                      12              1        (-inf.,1] 
 D             10                      8               2        (1,2] 
 A             4                       4               0        (-inf.,1] 
 B             6                       7               1        (-inf.,1] 
 C             12                      11              1        (-inf.,1]   
 A             9                       10              1        (-inf.,1] 

请您参考如下方法:

当您应用 .aggregate() 时,这些组将进入返回数据框的索引而不是列。您可以做的是将索引变成一个新列,例如:

df33['Bank'] = df33.index 

然后您可以筛选出感兴趣的组:

df44=df33[df33['Deviation']>=50] 

对于第二部分,你需要使用.isin():

workbook[workbook['Bank'].isin(df44['Bank'])]