2016-06-11 79 views
-1

我有我創建了一個數據透視表(數據透視表)循環:使用通過蟒蛇透視表

pivotTable= dayData.pivot_table(index=['sector'], aggfunc='count') 

已經產生了以下透視表:

    sector id 
broad_sector        
Communications   2 2 
Utilities    3 3 
Media     3 3 

可能有人讓我知道是否有方法通過數據透視表循環將索引值和扇區總數分配給各個變量sectorNamesectorCount

我試過了:

i=0 
while i <= lenPivotTable: 
    sectorName = sectorPivot.index.get_level_values(0) 
    sectorNumber = sectorPivot.index.get_level_values(1) 
    i=i+1 

返回第一個循環迭代:

sectorName = 'Communications' 
sectorCount = 2 

第二循環迭代:

sectorName = 'Utilities' 
sectorCount = 3 

第三循環迭代:

sectorName = 'Media' 
sectorCount = 3 

但可以不能讓它工作。任何幫助表示讚賞

+2

目前還不清楚是什麼你會實現。你能發佈一個理想的結果集嗎? – MaxU

+1

我不明白你的問題是什麼。這是關於[問] –

回答

1

好了,我不明白你爲什麼需要這個(因爲通過DF循環是非常慢),但你可以這樣來做:

In [403]: for idx, row in pivotTable.iterrows(): 
    .....:   sectorName = idx 
    .....:   sectorCount = row['sector'] 
    .....:   print(sectorName, sectorCount) 
    .....: 


Communications 2 
Utilities 3 
Media 3 
+0

的指南非常感謝,我仍在學習,所以這將幫助我在繼續之前瞭解基礎知識 – Stacey

0

此代碼段將爲您提供值的問題。

for sector_name, sector_count, _ in pivotTable.to_records(): 
    print(sector_name, sector_count)