mcpField
A
alterlab-datacommons

alterlab-datacommons

github.com/alterlab-ieu数据与数据库7868 次安装5 周前更新
代码仓库

关于 alterlab-datacommons

alterlab-datacommons 是面向 Python 用户的 Data Commons V2 客户端技能,用于查询统计数据、探索知识图谱并解析实体标识符。它涵盖从名称解析到 Pandas 分析的常见流程。

主要功能

  1. 01查询统计数据及时间序列
  2. 02探索实体属性与地理层级
  3. 03名称、坐标和外部 ID 解析
  4. 04将结果整理为 Pandas DataFrame

适用场景

  1. 01比较不同地区的人口或经济指标
  2. 02分析统计数据的历史趋势
  3. 03将地点名称转换为 DCID
  4. 04探索实体间的知识图谱关系

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/alterlab-ieu/alterlab-academic-skills --skill alterlab-datacommons

安装后在 Claude Code 中输入/alterlab-datacommons确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

evals/
evals.json
references/
getting_started.md
node.md
observation.md
resolve.md
scripts/
query_datacommons.py

详细介绍

Data Commons 客户端

概述

全面支持 Data Commons Python API v2,可用于查询统计观测数据、探索知识图谱以及解析实体标识符。Data Commons 将人口普查机构、卫生组织、环境机构及其他权威来源的数据汇总到统一的知识图谱中。

已针对 datacommons-client 2.1.6 进行验证(截至 2026-09 的当前版本;Python ≥ 3.10)。这是 V2 客户端(包 datacommons_client),不是旧版 datacommons(V1)包——两者的 API 不同;请勿混用。关键字名称很重要:地点层级辅助函数使用 place_dcids,fetch_entity_names 使用 entity_dcids,而 fetch_property_values 使用 properties——向它们传入 node_dcids 会引发 TypeError。

适用场景

  • 获取国家、州、县、市等地点的人口、经济、健康、教育或环境统计数据
  • 基于经过协调的公共数据源(人口普查、BLS、WHO、世界银行、EPA 等)构建跨地点或时间序列比较
  • 将地点名称、坐标或 Wikidata ID 解析为 Data Commons DCID
  • 探索 Data Commons 知识图谱(地点层级、属性、统计变量定义)
不适用场景
场景请改用
需要版本或修订数据的特定 FRED 经济序列(GDP、CPI、利率)alterlab-fred
美国财政部财政数据(债务、支出、收入)alterlab-usfiscaldata
NCI Imaging Data Commons(CT/MR/病理图像)——另一个名为“Data Commons”的项目alterlab-imaging-data-commons
几何图形的空间连接、缓冲区或制图alterlab-geopandas

安装

安装支持 Pandas 的 Data Commons V2 客户端(附加项名称为小写 pandas):

uv pip install "datacommons-client[pandas]"

不使用 Pandas 的基本用法:

uv pip install datacommons-client

核心功能

Data Commons API 由三个主要端点组成,每个端点的详细说明请参阅相应的参考文件:

1. Observation 端点——统计数据查询

查询实体的时间序列统计数据。完整文档请参阅 references/observation.md。

主要用途:

  • 获取人口、经济、健康或环境统计数据
  • 访问历史时间序列数据以分析趋势
  • 查询层级结构的数据(州内所有县、地区内所有国家)
  • 比较多个实体的统计数据
  • 按数据来源筛选,以确保一致性

常见模式:

from datacommons_client import DataCommonsClient

client = DataCommonsClient()

# Get latest population data
response = client.observation.fetch(
    variable_dcids=["Count_Person"],
    entity_dcids=["geoId/06"],  # California
    date="latest"
)

# Get time series
response = client.observation.fetch(
    variable_dcids=["UnemploymentRate_Person"],
    entity_dcids=["country/USA"],
    date="all"
)

# Query by hierarchy
response = client.observation.fetch(
    variable_dcids=["Median_Income_Household"],
    entity_expression="geoId/06<-containedInPlace+{typeOf:County}",
    date="2020"
)
2. Node 端点——知识图谱探索

探索知识图谱中的实体关系和属性。完整文档请参阅 references/node.md。

主要用途:

  • 发现实体可用的属性
  • 浏览地理层级(父子关系)
  • 获取实体名称和元数据
  • 探索实体之间的关联
  • 列出图谱中的所有实体类型

常见模式:

# Discover properties
labels = client.node.fetch_property_labels(
    node_dcids=["geoId/06"],
    out=True
)

# Navigate hierarchy (dict: DCID -> list of {"dcid", "name", "types"})
children = client.node.fetch_place_children(
    place_dcids="country/USA",
    children_type="State",
)

# Get entity names (dict: DCID -> Name(value=..., language=...))
names = client.node.fetch_entity_names(
    entity_dcids=["geoId/06", "geoId/48"]
)
3. Resolve 端点——实体识别

将实体名称、坐标或外部 ID 转换为 Data Commons ID(DCID)。完整文档请参阅 references/resolve.md。

主要用途:

  • 将地点名称转换为查询所需的 DCID
  • 根据坐标解析地点
  • 将 Wikidata ID 映射到 Data Commons 实体
  • 处理有歧义的实体名称

常见模式:

# Resolve by name
response = client.resolve.fetch_dcids_by_name(
    names=["California", "Texas"],
    entity_type="State"
)

# Resolve by coordinates (returns a ResolveResponse, not a bare DCID)
coord_response = client.resolve.fetch_dcid_by_coordinates(
    latitude="37.7749",
    longitude="-122.4194"
)

# Resolve Wikidata IDs
response = client.resolve.fetch_dcids_by_wikidata_id(
    wikidata_ids=["Q30", "Q99"]
)

典型工作流

大多数 Data Commons 查询都遵循以下模式:

  1. 解析实体(如果起始信息是名称):

    resolve_response = client.resolve.fetch_dcids_by_name(
        names=["California", "Texas"], entity_type="State"
    )
    # to_dict() -> {"entities": [{"node": "California", "candidates": [{"dcid": ...}]}, ...]}
    dcids = [e["candidates"][0]["dcid"]
             for e in resolve_response.to_dict()["entities"]
             if e.get("candidates")]
    # or: resolve_response.to_flat_dict() -> {"California": "geoId/06", ...}
    #     (a list of DCIDs when the name is ambiguous)
    
  2. 发现可用变量(可选):

    variables = client.observation.fetch_available_statistical_variables(
        entity_dcids=dcids
    )
    
  3. 查询统计数据:

    response = client.observation.fetch(
        variable_dcids=["Count_Person", "UnemploymentRate_Person"],
        entity_dcids=dcids,
        date="latest"
    )
    
  4. 处理结果:

    # As dictionary
    data = response.to_dict()
    
    # As flat records (date, entity, variable, value + facet metadata).
    # to_observation_records() returns a pydantic model — dump it before
    # building a DataFrame, or the columns come out as 0..N.
    records = response.to_observation_records().model_dump()
    df = pd.DataFrame(records)
    

    如果想跳过手动转换,客户端还提供了专用的 DataFrame 访问器,可执行相同的查询并直接返回整洁的 DataFrame:

    df = client.observations_dataframe(
        variable_dcids=["Count_Person"],
        entity_dcids=["geoId/06", "geoId/48"],
        date="all",
    )
    

查找统计变量

Data Commons 中的统计变量遵循特定的命名模式:

常见变量模式:

  • Count_Person — 总人口
  • Count_Person_Female — 女性人口
  • UnemploymentRate_Person — 失业率
  • Median_Income_Household — 家庭收入中位数
  • Count_Death — 死亡人数
  • Median_Age_Person — 年龄中位数

发现方法:

# Check what variables are available for an entity
available = client.observation.fetch_available_statistical_variables(
    entity_dcids=["geoId/06"]
)

# Or explore via the web interface
# https://datacommons.org/tools/statvar

使用 Pandas

惯用的方式是使用客户端的 observations_dataframe() 访问器。它沿用 observation.fetch() 的参数,但一次调用即可返回整洁的 DataFrame(需要 pandas extra):

df = client.observations_dataframe(
    variable_dcids=["Count_Person"],
    entity_dcids=["geoId/06", "geoId/48"],
    date="all",
)
# Columns: date, entity, variable, value (plus facet/provenance columns)

# Reshape for analysis
pivot = df.pivot_table(
    values='value',
    index='date',
    columns='entity'
)

要获取父级地点下某一类型的所有实体,请将 entity_dcids="all" 与 entity_type 和 parent_entity 一起传入:

df = client.observations_dataframe(
    variable_dcids=["Median_Income_Household"],
    date="latest",
    entity_dcids="all",
    entity_type="County",
    parent_entity="geoId/06",
)

如果已有响应对象,可使用 to_observation_records() 将其展平 (注意是单数形式的 “observation”;不存在 to_observations_as_records),然后将其导出:

response = client.observation.fetch(
    variable_dcids=["Count_Person"],
    entity_dcids=["geoId/06", "geoId/48"],
    date="all",
)
df = pd.DataFrame(response.to_observation_records().model_dump())

API 身份验证

对于 datacommons.org(默认):

  • 查询观测值和节点需要 API 密钥(未经身份验证的调用会返回 HTTP 401 UNAUTHENTICATED);名称解析目前无需密钥即可响应
  • 通过环境变量设置:export DC_API_KEY="your_key"
  • 或在初始化时传入:client = DataCommonsClient(api_key="your_key")
  • 在此申请密钥:https://apikeys.datacommons.org/

对于自定义 Data Commons 实例:

  • 无需 API 密钥
  • 指定自定义端点:client = DataCommonsClient(url="https://custom.datacommons.org")

参考文档

references/ 目录中提供了各个端点的完整文档:

  • references/observation.md:完整的 Observation API 文档,包含所有方法、参数、响应格式和常见用例
  • references/node.md:完整的 Node API 文档,介绍图探索、属性查询和层级导航
  • references/resolve.md:完整的 Resolve API 文档,介绍实体识别和 DCID 解析
  • references/getting_started.md:快速入门指南,包含端到端示例和常见模式

其他资源

高效使用技巧

  1. 始终从解析开始:先将名称转换为 DCID,再查询数据
  2. 使用关系表达式处理层级:一次查询所有子项,而不是逐个查询
  3. 先检查数据是否可用:使用 fetch_available_statistical_variables() 查看可查询的内容
  4. 利用 Pandas 集成:将响应转换为 DataFrame 以便分析
  5. 缓存解析结果:如果反复查询相同实体,请存储名称→DCID 映射
  6. 按 facet 筛选以确保一致性:使用 filter_facet_domains 确保数据来自同一来源
  7. 阅读参考文档:每个端点的详细文档都位于 references/ 目录中

脚本

scripts/query_datacommons.py — 可运行的 Data Commons REST v2 API 辅助脚本(需要在 DC_API_KEY 中设置免费密钥):

python scripts/query_datacommons.py resolve "California" --type State
python scripts/query_datacommons.py observe Count_Person geoId/06 --date latest

评论

支持 Markdown