首页 > 解决方案 > ValueError: 期望 dict 或 pandas.DataFrame

问题描述

我正在尝试创建一个分类 vBar,它将显示为各种操作拾取的迁移总数,但是,当我将“groupby”pandas 对象传递到列数据源时,我不断收到错误,我不太清楚确定我做错了什么。

我在几个地方寻找过类似的问题,但似乎找不到任何答案。

谁能指出我正确的方向?

#Imports
import pandas as pd
from bokeh.io import curdoc
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource
from bokeh.models.tools import HoverTool
from bokeh.models import Button
from bokeh.layouts import row

#Global variables
viewFilter='Operation'

#Data
df = pd.read_csv('data.csv')
grouped = df.groupby(viewFilter)['Total Migrants']
source = ColumnDataSource(grouped)
#grouped = df.groupby(viewFilter)['Total Migrants'].sum()
#source = ColumnDataSource(pd.DataFrame(grouped))
operations = source.data[viewFilter].tolist()

# Fig Creation Function 
def create_figure():
    global viewFilter
    p=figure(x_range=operations)
    p.vbar(x=viewFilter, top='Total Migrants', 
           source=source, width=0.70)

    p.title.text='Demo Chart'
    p.xaxis.axis_label = viewFilter
    p.yaxis.axis_label = 'Total Migrants'

    #Hover took
    hover = HoverTool()
    hover.tooltips=[
        ("Total Migrants Rescued", "@{Total Migrants}")]
    hover.mode='vline'
    p.add_tools(hover)

    return p

#Update Data with Ship-level aggregation
def shipUpdate():
    print("Ship Button was Pushed")

#Widgets
shipButton = Button(label='Ship Level')
shipButton.on_click(shipUpdate)

#Implement Layout
layout = row(shipButton, create_figure())

#Add Layout to Document
curdoc().add_root(layout)

标签: pythonpandasbokeh

解决方案


看起来在 groupby() 方法或 ColumnDataSource() 中传递了错误的参数值

句法:

DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, observed=False, **kwargs)

参数 by-> list, str, dict

ColumnDataSource 的构造函数的代码片段如下 -

def __init__(self, *args, **kw):
        ''' If called with a single argument that is a dict or
        pandas.DataFrame, treat that implicitly as the "data" attribute.

        '''
        if len(args) == 1 and "data" not in kw:
            kw["data"] = args[0]

        # TODO (bev) invalid to pass args and "data", check and raise exception
        raw_data = kw.pop("data", {})

        if not isinstance(raw_data, dict):
            if pd and isinstance(raw_data, pd.DataFrame):
                raw_data = self._data_from_df(raw_data)
            elif pd and isinstance(raw_data, pd.core.groupby.GroupBy):
                raw_data = self._data_from_groupby(raw_data)
            else:
                raise ValueError("expected a dict or pandas.DataFrame, got %s" % raw_data)
        super(ColumnDataSource, self).__init__(**kw)
        self.data.update(raw_data)

推荐阅读