API输出转DataFrame最简方法及ACLED数据读取空表问题排查
Hey there! Let's break down your questions and fix that ACLED API issue step by step.
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 topd.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
datafield holding the records):
Extract the specific key (usuallydata) that contains the dataset array first:df = pd.DataFrame(response.json()['data']) - If the API supports CSV output:
Skip the JSON parsing entirely and usepd.read_csv()directly with the API URL that returns CSV.
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

