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

如何将免费汇率API返回的JSON转换为指定结构的Pandas DataFrame

解决汇率API数据转指定格式Pandas DataFrame的问题

完整实现代码

import requests
import pandas as pd

# 获取API数据
url = 'https://api.exchangerate.host/latest?base=USD'
response = requests.get(url)
data = response.json()

# 提取全局字段
base_currency = data['base']
date = data['date']

# 将汇率字典转换为DataFrame
rates_df = pd.DataFrame.from_dict(data['rates'], orient='index', columns=['rate'])
rates_df.reset_index(inplace=True)
rates_df.rename(columns={'index': 'currency'}, inplace=True)

# 添加上全局字段
rates_df['base'] = base_currency
rates_df['date'] = date

# 调整列顺序为目标格式
final_df = rates_df[['date', 'base', 'currency', 'rate']]

# 查看结果(可选)
print(final_df.head())

# 存储数据(可选,示例为CSV格式)
# final_df.to_csv('exchange_rates.csv', index=False)

步骤说明

  1. 提取全局字段:从API返回的JSON中取出base(基准货币)和date(日期),这两个值需要对应每一条汇率数据。
  2. 转换汇率字典:用pd.DataFrame.from_dict把rates字典转为DataFrame,orient='index'表示将字典的键(货币代码)作为行索引,之后通过reset_index把索引转为普通列并命名为currency。
  3. 合并全局字段:直接给DataFrame新增base和date列,因为这两个值对所有行一致,批量赋值即可。
  4. 调整列顺序:通过列名列表重新排列DataFrame的列,匹配你需要的结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 05:03:36