Home > Mobile >  How do you remove a row in a pivot table in pandas?
How do you remove a row in a pivot table in pandas?

Time:06-03

I used this code to create a pivot in pandas:

table = pd.pivot_table(df, values='Value (millions)', index=['TierA', 'TierB'], aggfunc=['count',np.sum])

This gives me the pivot:

                      count               sum
                 Value (millions)   Value (millions)
TierA   TierB   
1        1             6                    400
2        0             0                     0
2        2             1                    300

In a pivot table how do I remove the [2,0,0,0] row? I tried the normal:

table = table.drop(['TierA','TierB','count','sum'], axis =0)

It didn't work, and neither did this: table = table.drop(['TierA','TierB','Value (millions)'], axis =0)

Is what i'm trying to do possible? If so, how would I go about it?

Thanks

CodePudding user response:

This depends on why you want to drop the row.

If it's because its index is (2,0), then write table.drop(index = (2,0)) or table.drop(index = 0, level = 1).

If it's because some of the values are 0, then write table.loc[~(table.count == 0)] or table.loc[~(table.sum == 0)]

I find it is often more convenient to .loc the inverse of the thing you want to remove, using ~ before the boolean condition, rather than dropping rows.

CodePudding user response:

Your pivot_table has a MultiIndex and you have to pass a tuple to drop the row. Try with

table = table.drop((2, 0), axis = 0)
  • Related