python - 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)
解决方案
看起来在 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)
推荐阅读
- java - bound mismatch 如何匹配它们?
- ms-access - Microsoft Access:查询涉及一个父多个子,每个父只选择最高值的子
- javascript - 访问 Objects 实例构造函数以进行克隆
- r - 使用axis() R plot 设置坐标轴。基数 R,出版数字
- javascript - TypeError:尝试访问对象数组中的数据时无法读取未定义的属性“标题”
- ios - 使用 CKAsset 在 CloudKit 中创建记录,但获取时资产始终为零,其他属性正常
- java - 调用递归的参数
- android - ArrayAdapter 去掉错了吗?
- sql - 我需要在 SAS 中使用 if 语句创建变量吗?
- javascript - 如何将 CSS 文件导入 React JS 应用程序?