如何在pandas的数据透视表中搜索数据?

时间:2017-03-23 19:16:18

标签: python pandas dataframe pivot-table

我使用以下方法从数据框创建了一个数据透视表:

table = pd.pivot_table(df , index=['student','year','subject'] , values=['mark'])

我有一张这样的桌子:

student       year        subject 

'Martin'      2014        Algebra      5
                          Chemistry    3.5 
                          Programming  8

'Sara'        2013        Algebra 2.2
 ....         ....        .....

我怎样才能获得Martin 2014 Algebra的标志?

我尝试过作为数据框:

 t[t.student=='Martin'][t.year=2014][t.subject==Algebra]

但它不起作用

有人能帮助我吗?感谢的!

4 个答案:

答案 0 :(得分:3)

您需要重置索引才能使用布尔索引

t= table.reset_index()
t[(t.student=='Martin') & (t.year=2014) & (t.subject=='Algebra')]

或者您可以使用MultiIndex Selection

table.loc[('Martin', 2014, 'Algebra')]

答案 1 :(得分:2)

您有一个多索引数据框,使用带有元组的loc来访问该值:

table.loc[("'Martin'",2014,"Algebra")]

答案 2 :(得分:1)

生成的数据透视表只是另一个数据帧。但是,此数据框具有多索引。可以使用级别的元组引用多索引。这是@ psidom和@ TedPetrou的答案

但是,另一种方法是使用xs cross section method

table.xs(('Martin', 2014, 'Algebra'))

在这种特殊情况下,桌子实际上是一个系列。您可以在数据框上使用query。因此,我们可以将其设为数据框,然后query

table.to_frame().query('student == "Martin" & year == 2014 & subject == "Algebra"')

答案 3 :(得分:0)

数据透视表中的多个索引会导致您的语句出现问题,请在下面使用

table.loc[('Martin', 2014, 'Algebra')]