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

API输出转DataFrame最简方法及ACLED数据读取空表问题排查

Hey there! Let's break down your questions and fix that ACLED API issue step by step.

1. 最简方法:将API输出转换为DataFrame

The simplest approach depends on what format the API returns:

  • If the API returns a JSON array (directly a list of records):
    Just pass the parsed JSON directly to pd.DataFrame():
    import pandas as pd
    import requests
    
    response = requests.get("your_api_url")
    df = pd.DataFrame(response.json())
    
  • If the API returns a nested JSON (with a data field holding the records):
    Extract the specific key (usually data) that contains the dataset array first:
    df = pd.DataFrame(response.json()['data'])
    
  • If the API supports CSV output:
    Skip the JSON parsing entirely and use pd.read_csv() directly with the API URL that returns CSV.
2. 解决ACLED API读取返回空DataFrame的问题

Your original code fails because you're using pd.read_csv() to read a JSON response. Let's look at why and fix it:

What went wrong?

The URL you used appended .csv to the end, but the ACLED API is still returning a JSON structure (as shown in your output). The CSV parser can't interpret this JSON as valid CSV, so it treats the entire JSON string as a single column name with no data rows—hence the empty DataFrame.

Fixed Code

Use requests to fetch the JSON data, extract the data array from the response, then convert it to a DataFrame:

import requests
import pandas as pd

# Fetch the JSON data from ACLED API
url = "https://api.acleddata.com/acled/read?terms=accept&country=Afghanistan&date=20200315"
response = requests.get(url)

# Ensure the request succeeded
response.raise_for_status()

# Parse JSON and convert the 'data' array to DataFrame
acled_data = response.json()
AcledData = pd.DataFrame(acled_data['data'])

# Check the result
print(AcledData.head())

This will correctly load the event records into a DataFrame with proper columns and rows.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 07:24:12