如何在python中编写交叉表查询?

问题描述

我在python中有一个在数据框上使用交叉表的函数

def event_mouhafaza(self,df):
        df_event_mohafazat_crosstab = pd.crosstab(df['event_mohafaza'],df['event_type'])
        print(df_event_mohafazat_crosstab)        

上面的函数可以正常工作,并返回预期的结果。

当我尝试用变量替换交叉表查询的值时,系统崩溃。

def event_mouhafaza(self,df,items):
   
     for item in items:
         item1 = items[0]
         item2 = items[1]
        
     df = df.set_index(item2)    
     df_event_mohafazat_crosstab = pd.crosstab(df,item1,item2)
     print(df_event_mohafazat_crosstab)

显示错误

df_event_mohafazat_crosstab = pd.crosstab(df,item2)
  File "F:\AIenv\lib\site-packages\pandas\core\reshape\pivot.py",line 577,in crosstab
    raise ValueError("values cannot be used without an aggfunc.")
ValueError: values cannot be used without an aggfunc.

第二个功能错误在哪里以及如何解决

解决方法

在第二个示例中,您使用的交叉表功能错误。 pd.crosstab并不将数据框作为其第一个参数。现在,您正在像这样调用函数(使用kwargs突出显示问题)。当您指定values参数时(就像您使用位置参数一样),pandas也希望将某些内容传递到aggfunc参数中。有关更多信息,请参见文档。

# This will error out.
pd.crosstab(index=df,columns=item1,values=item2)

如果item1item2是数据框中的列名,则需要执行以下操作:

pd.crosstab(index=df[item1],columns=df[item2])

接下来,如果您打算在交叉表中使用item2,则实际上并不想将其设置为索引。而且您的for循环实际上没有执行任何操作,您可以在没有它的情况下分配item1和item2:

def event_mouhafaza(self,df,items):
   
     item1 = items[0]
     item2 = items[1]
        
     df_event_mohafazat_crosstab = pd.crosstab(index=df[item1],columns=df[item2])
     print(df_event_mohafazat_crosstab)