如何将API获取的字符串数组转换为Pandas DataFrame?
Convert API JSON Array to Single-Column Pandas DataFrame
Got it, let's break this down simply. Your API returns a JSON object where the trendingEntities key holds the list of terms you need. The fix is straightforward—you just need to extract that list and feed it directly into the Pandas DataFrame constructor.
Step-by-Step Solution
- Parse the JSON response: Instead of printing
response.text, useresponse.json()to convert the JSON string into a Python dictionary. - Extract the entities list: Pull out the
trendingEntitiesarray from the dictionary. - Create the DataFrame: Pass the list to
pd.DataFrame()—Pandas will automatically create a single column with the default header0and sequential index, which matches exactly what you need for Power BI.
Modified Working Code
import requests import pandas as pd url = "https://api.newswhip.com/v1/trendingEntities?key=XXX" payload = { "filters": ["categories: 33"], "from": None, "to": None } headers = { "accept": "application/json", "content-type": "application/json" } response = requests.post(url, json=payload, headers=headers) # Parse the JSON response into a dictionary data = response.json() # Extract the list of trending entities trending_entities = data['trendingEntities'] # Convert the list to a single-column DataFrame df = pd.DataFrame(trending_entities) # Verify the output print(df)
Sample Output
This will produce exactly the format you're looking for:
0 0 Charlton 1 Spanish Super Cup 2 North London Derby 3 Bruno Fernandes 4 Rodrygo ... 12 FIFA Best 13 Aaron Ramsdale 14 Kai Havertz
Bonus: Custom Column Name (Optional)
If you want a more descriptive column name instead of 0 (which might be better for Power BI readability), just specify the columns parameter:
df = pd.DataFrame(trending_entities, columns=["Trending Entities"])
That's it—this should work seamlessly with Power BI when you load the DataFrame.
内容的提问来源于stack exchange,提问作者RogueSergeant
相关产品推荐
相关产品推荐

