如何在可视化的大熊猫和python中编写交叉表查询

问题描述

函数显示交叉表表并使用matplotlib可视化结果。

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

        data = []
        #use for loop on every zoo name to create bar data
        for x in df_event_mohafazat_crosstab.columns:
            data.append(go.Bar(name=str(x),x=df_event_mohafazat_crosstab.index,y=df_event_mohafazat_crosstab[x]))

        layout = go.Layout(
            title = "Event type over Location",xaxis=dict(
            title="Mouhafazat"
            ),yaxis=dict(
            title="Number of people"
            )
        )

        figure = go.figure(data,layout=layout)
        plotly.offline.plot(figure)

下表是预期结果

event_type      watch movie stay at home swimming   camping  meeting
event_mohafaza
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

这是可视化的结果

enter image description here

尝试将上面的代码转换为下面的代码在这里我从函数获取参数并在交叉表查询中使用它。

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

    data = []
    #use for loop on every zoo name to create bar data
    for x in df_event_mohafazat_crosstab.columns:
        data.append(go.Bar(name=str(x),y=df_event_mohafazat_crosstab[x]))

    layout = go.Layout(
        title = "Event type over Location",xaxis=dict(
        title="Mouhafazat"
        ),yaxis=dict(
        title="Number of people"
        )
    )

    figure = go.figure(data,layout=layout)
    plotly.offline.plot(figure)

但系统崩溃并显示错误

    df_event_mohafazat_crosstab = pd.crosstab(item1,index=item1)
TypeError: crosstab() got multiple values for argument 'index'

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)