Stacey Stacey - 4 months ago 12x
Python Question

Looping through a python pivot table

I have a pivot table that I have created (pivotTable) using:

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

which has produced the following pivot table:

sector id
Communications 2 2
Utilities 3 3
Media 3 3

Could someone just let me know if there is a way to loop through the pivot table assigning the index value and sector total to respective variables

I have tried:

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

to return for the first loop iteration:

sectorName = 'Communications'
sectorCount = 2

for the second loop iteration:

sectorName = 'Utilities'
sectorCount = 3

for the third loop iteration:

sectorName = 'Media'
sectorCount = 3

But can't get it to work. Any assistance appreciated


well, i don't understand why do you need this (because looping through DF is very slow), but you can do it this way:

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

Communications 2
Utilities 3
Media 3