2017-10-20 119 views
1

我在Pandas的groupby函数中传递级别名称时遇到问题。我的数据框非常大,有34列。如何在Pandas的groupby函数中将列名传递给level参数?

Shpr_Resi_Ratio = (
    data[data.Resi == 'Y'].groupby(level='Shpr_ID').count()/
    data.groupby(level='Shpr_ID').count() 
) 

错误

2523      raise ValueError('level name %s is not the name of the ' 
-> 2524          'index' % level) 
    2525    elif level > 0 or level < -1: 
    2526     raise ValueError('level > 0 or level < -1 only valid with ' 

ValueError: level name Shpr_ID is not the name of the index 

如何解决这个问题

样品数据帧

Stop_Type Resi Co_Name Lat Lng Cust_ID Qty Phone Shpr_ID 
0 D N ROBECO HONG KONG 22.283737 114.156219 NaN 1 0 348772830.0 
1 D N NIKKO ASSET MANAGEMENT HK LIMI 22.283737 114.156219 NaN 1 85239403900 811633127.0 
2 D N CFA INSTITUTE HONG KONG OFFICE 22.283737 114.156219 NaN 1 8.52E+11 22901265.0 
3 D N VICTON REGISTRATIONS LIMITED 22.283144 114.155122 NaN 1 85228450884 269243180.0 
4 D N DING FUNG LIMITED 22.282634 114.155592 NaN 1 85223919307 100724987.0 
5 D N QUAM LIMITED 22.281737 114.156819 NaN 6 85222172878 193550630.0 
6 D N CANARA BANK 22.281737 114.156819 NaN 1 85225291398 911433524.0 
7 D N GIA HONG KONG 22.281737 114.156819 NaN 1 85223030075 90470655.0 
8 D Y ZAABA CAPITAL LIMITED 22.281737 114.156819 NaN 1 8772461225 260103490.0 
9 D N FIRESTAR DIAMOND HK 22.280644 114.158432 NaN 1 25303677 659886588.0 

我试图计算比例的两种cloumns。

Resi Shpr_ID Shpr_ID_Ratio 
Y 577030944 0.933333333 
N 577030944 0.933333333 
Y 577030944 0.933333333 
Y 577030944 0.933333333 
Y 577030944 0.933333333 
Y 577030944 0.933333333 
Y 577030944 0.933333333 
Y 577030944 0.933333333 
Y 577030944 0.933333333 
Y 577030944 0.933333333 
Y 577030944 0.933333333 
Y 577030944 0.933333333 
Y 577030944 0.933333333 
Y 577030944 0.933333333 
Y 577030944 0.933333333 
+0

你可以添加一个样本数据,比如'Shpr_Resi_Ratio.head()。iloc [:,:5]'。是您指数多指标()?如果没有尝试'级= 0' – Dark

+0

@Bharathshetty,输出top_Type \t住宅建设\t Co_Name \t纬度\t LNG Shpr_ID \t \t \t \t \t 1.0 \t NaN的\t NaN的\t NaN的\t NaN的\t NaN的 30.0 \t \t的NaN NaN的\t \t的NaN NaN的\t的NaN 132.0 \t \t的NaN NaN的\t \t的NaN NaN的\t的NaN 148.0 \t \t的NaN NaN的\t \t的NaN NaN的\t的NaN 156.0 \t \t的NaN NaN的\t \t的NaN NaN的\t的NaN –

+0

对不起它被假设是'data.head(10).iloc [:,:5]' 。在你的qn – Dark

回答

0

您是否试图将'Shpr_ID'列分组?

在这种情况下,更改代码:

Shpr_Resi_Ratio = (
    data[data.Resi == 'Y'].groupby(['Shpr_ID']).count()/
    float(data.groupby(['Shpr_ID']).count()) 
) 

应采取照顾。

+0

中增加了我的预期输出,它不计算比率 –

+0

是由不计数的浮点数引起的?我已经编辑了我的答案,将其纳入本文。 – Prikkel

+0

它给再次error.TypeError:float()参数必须是一个字符串或数字,而不是'DataFrame' –

0
Shpr_ID_total=data.groupby(['Shpr_ID']).agg({'Shpr_ID': 'count'}) 
Shpr_ID_Y=data[data['Resi'] == 'Y'].groupby(['Shpr_ID']).agg({'Shpr_ID': 'count'}) 

def computeResi(Shpr_ID): 
    ratio=0 

    try: 
     ratio=Shpr_ID_Y.Shpr_ID[Shpr_ID]/Shpr_ID_total.Shpr_ID[Shpr_ID] 
    except: 
     pass 

    return ratio 
相关问题