Amos Chew
Amos Chew

Reputation: 137

Pandas pivot table raise KeyError(i)

I'm just trying out the pivot_table code in pandas. I have a Dataframe below:

Device Name   Remark
NodeX         Hardware
NodeX         Software
NodeY         Hardware
NodeY         Hardware
NodeZ         Software
NodeZ         Software

and expected output of the pivot table is the total count for each category in 'Remark' for each 'Device Name':

Device Name  Hardware   Software
NodeX        1          1
NodeY        2          0
NodeZ        0          2

the code for pivot_table is

dfsummary = pd.pivot_table(df, index=['Device Name'], columns='Remark', values=['Hardware', 'Software'], aggfunc='count', fill_value=0)

but I'm receiving this error:

...., in pivot_table raise KeyError(i)
KeyError: 'Hardware'

This is an example of a similar scenario that I'm facing when using pivot_table.

Upvotes: 1

Views: 1330

Answers (2)

Scott Boston
Scott Boston

Reputation: 153460

Use pd.crosstab:

pd.crosstab(df['Device Name'], df['Remark'])

Output:

Remark       Hardware  Software
Device Name                    
NodeX               1         1
NodeY               2         0
NodeZ               0         2

Upvotes: 2

YOLO
YOLO

Reputation: 21719

You can try something like this:

pd.pivot_table(df, index='Device Name', columns='Remark', aggfunc='size', fill_value=0)

Upvotes: 2

Related Questions