2017-10-20 116 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 
相關問題