Glenn G.
Glenn G.

Reputation: 419

Key Error pivot table pandas

Trying to drop certain row from pivot table. However, whenever I try to drop the row I get a key error. I've looked into reshaping pivot tables and multi-indexing, but I'm having trouble grasping the concepts. Are they even necessary for this situation? If so, can you please explain? If not, what's the most efficient way to fix the issue?

ps_total = ps.pivot_table(index="CountyName",columns="Year",values=["Number of Private Schools"],aggfunc=np.sum)
ps_total.columns = pd.MultiIndex.from_tuples(ps_total.columns) 
ps_total = ps_total[(ps_total["CountyName"]==1).any(axis=1)] # error here
ps_total = ps_total.fillna(0)
print(ps_total.to_string())



                                     2010   2011   2012   2013   2014   2015  
CountyName                                                                         
1                                     0.0    0.0    0.0    0.0    0.0    3.0    
Alameda                             156.0  144.0  148.0  145.0  141.0  136.0  
Alpine                                0.0    0.0    1.0    1.0    0.0    0.0    
Amador                                2.0    2.0    1.0    1.0    1.0    0.0    
Butte                                21.0   21.0   22.0   21.0   19.0   16.0  

 Key Error: "CountyName"

Upvotes: 1

Views: 529

Answers (1)

DYZ
DYZ

Reputation: 57033

ps_total is a MultiIndex named "CountyName". It does not have the key "CountyName". You are probably looking for ps_total==1.

Upvotes: 1

Related Questions