像普通的datafram一样过滤pandas pivot_表结果

2024-05-17 19:05:27 发布

您现在位置:Python中文网/ 问答频道 /正文

当我尝试过滤Pandas数据帧时,就像下面的例子一样,它工作得很好:

print data[data['ProductCategory'].isin(['ProductA'])]

但当我尝试对生成的透视表执行相同操作时:

^{pr2}$

我得到一个关键错误:

File "pandas\index.pyx", line 134, in pandas.index.IndexEngine.get_loc (pandas\index.c:3838) File "pandas\index.pyx", line 154, in pandas.index.IndexEngine.get_loc (pandas\index.c:3718) File "pandas\hashtable.pyx", line 686, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12294) File "pandas\hashtable.pyx", line 694, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12245) KeyError: 'ProductCategory'

透视表的describe()给出了:

        FxRate           Price        Quantity
count   48.00           48.00           48.00
mean     0.93    4,717,051.34   46,446,338.82
std      0.20   20,603,134.35  188,008,495.83
min      0.64  -16,088,043.02 -137,804,378.35
25%      0.73      -87,306.39           83.75
50%      1.00       41,198.26      682,025.97
75%      1.00    2,999,491.53    7,489,198.82
max      1.25  137,804,362.15  939,610,000.00

A数据透视.info()给出以下输出:

 <class 'pandas.core.frame.DataFrame'>
MultiIndex: 48 entries, (ProductA, ProductB, ProductC) to (ProducerA, ProducerB, ProducerC)
Data columns (total 3 columns):
FxRate         48 non-null float64
Price          48 non-null float64
Quantity       48 non-null float64
dtypes: float64(3)

memory usage: 2.3+ KB
None

还有一个枢轴.头部()给出了:

                                          FxRate      Price   Quantity  
ProductCategory Currency      Producer                                 
ProductA        EUR           ProducterA   1.00       0.90       1.10   
                              ProducterB   1.00       0.90       1.10   
                GBP           ProducterB   1.25       1.12       1.37   
ProductB        EUR           ProducterA   1.00       0.90       1.10   
                GBP           ProducterC   1.25       1.12       1.37

Tags: inpandasgetindexlinepricequantityfile
1条回答
网友
1楼 · 发布于 2024-05-17 19:05:27

ProductCategoryCurrency和{}现在是groupby操作后索引的一部分。尝试重置名为pivot.reset_index(inplace=True)的数据帧的索引,然后像往常一样使用loc进行选择。在

>>> pivot[pivot['ProductCategory'].isin(['ProductA'])]
  ProductCategory Currency    Producer  FxRate  Price  Quantity
0        ProductA      EUR  ProducterA    1.00   0.90      1.10
1        ProductA      EUR  ProducterB    1.00   0.90      1.10
2        ProductA      GBP  ProducterB    1.25   1.12      1.37

如果需要,可以重置结果的索引。在

或者,您可以在原始的pivot上使用loc,如下所示:

^{pr2}$

相关问题 更多 >