熊猫交叉表查询中的错误在哪里

问题描述

我具有包含crosstab查询的Python函数,但是系统崩溃并显示以下错误

ValueError: If using all scalar values,you must pass an index

DF样品:

enter image description here

预期结果:

event_type      watch movie stay at home swimming   camping  meeting
event_location
loc1            0              65           0       254      13
loc2           60              0           125      19
loc3          518              3           705      87
loc4          721              11          318      147
loc5            0             103            0      214      17

在调试过程中,它表明item1item2的分配正确。

代码

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

解决方法

交叉表应首先通过索引:

df = df.set_index('event_type ')    
df_event_loc_crosstab = pd.crosstab(event_type,event_location)