You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将wbgapi.Coder元素转为pandas DataFrame?解决值错误问题

解决wbgapi.Coder字典转pandas DataFrame的ValueError问题

你遇到的错误是因为wb.economy.coder()返回的是键为国家名称、值为对应代码的单层字典,所有值都是标量类型,直接用默认参数的pd.DataFrame.from_dict()无法生成DataFrame——pandas需要明确的行/列结构。

以下是几种可行的解决方法:

方法1:转成键值对列表构建DataFrame

把字典的键值对转成列表,让pandas自动生成两列结构:

import wbgapi as wb
import pandas as pd

# 获取coder字典
coder_data = wb.economy.coder(['Rwanda', 'Bolivia'])
# 从键值对列表创建DataFrame,指定列名
df = pd.DataFrame(coder_data.items(), columns=['Country', 'Code'])

生成的DataFrame会有Country(国家名称)和Code(对应代码)两列,索引从0开始。

方法2:以国家名为索引构建DataFrame

如果你希望把国家名称作为行索引,代码作为单独列,可以指定orient='index':

df = pd.DataFrame.from_dict(coder_data, orient='index', columns=['Code'])
# 给索引命名,让结构更清晰
df.index.name = 'Country'

这种方式下,行是国家名称,列是对应的代码。

方法3:通过Series中转

先把字典转成pandas Series,再转成DataFrame:

# 创建Series并指定列名
country_series = pd.Series(coder_data, name='Code')
# 转成DataFrame并重置索引,重命名索引列为Country
df = country_series.to_frame().reset_index().rename(columns={'index': 'Country'})

最终效果和方法1一致。

错误原因说明

pd.DataFrame.from_dict()默认使用orient='columns'模式,即把字典的键作为列名,值作为该列的所有行数据。但你的字典中每个值都是单个标量(不是数组/列表),pandas无法确定需要多少行,因此抛出ValueError: If using all scalar values, you must pass an index的错误。上述方法通过调整数据结构或指定orient参数,解决了这个问题。

内容的提问来源于stack exchange,提问作者marimachine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 21:15:41