如何使用Python的DataFrame将数组转换为CSV格式并处理RestAPI返回数据的格式转换?
Got it, let's break this down step by step for you—we'll cover transforming the API data, turning it into a pandas DataFrame, and exporting it to a CSV file.
Step 1: Restructure the API Response Data
Your original API data uses product names as top-level keys with nested attribute dictionaries. We need to shift this into a column-oriented format (note: I’ll use lists instead of sets here because sets are unordered and can mess up data alignment—if you specifically need sets, you can convert the lists later, but lists are far more compatible with pandas).
Here’s how to do it with plain Python:
# Original API response data data = { "apple": {"price": 0.89, "category": "fruit", "weight": 13.88}, "carrot": {"price": 1.87, "category": "vegetable", "weight": 3.23} } # Convert to column-focused structure formatted_data = { "product": list(data.keys()), "price": [item["price"] for item in data.values()], "category": [item["category"] for item in data.values()], "weight": [item["weight"] for item in data.values()] }
If you absolutely need sets (though I don’t recommend it for DataFrames), just cast each list to a set:
formatted_data_with_sets = { "product": set(data.keys()), "price": set(item["price"] for item in data.values()), "category": set(item["category"] for item in data.values()), "weight": set(item["weight"] for item in data.values()) }
Step 2: Convert to a pandas DataFrame
Once you have the column-oriented data, creating a DataFrame is super straightforward:
import pandas as pd # Create DataFrame from the formatted data df = pd.DataFrame(formatted_data)
You can check what the DataFrame looks like with a quick print:
print(df)
This will output:
product price category weight 0 apple 0.89 fruit 13.88 1 carrot 1.87 vegetable 3.23
Bonus: Skip Manual Formatting
You don’t even need to restructure the data manually—pandas can handle the original nested dictionary directly with from_dict():
df = pd.DataFrame.from_dict(data, orient='index').reset_index() df.rename(columns={'index': 'product'}, inplace=True)
This gets you the exact same DataFrame with less code.
Step 3: Export the DataFrame to CSV
To save the DataFrame as a CSV file, use the to_csv() method. The index=False parameter ensures we don’t include pandas’ default index column in the output:
# Export to CSV file df.to_csv('products.csv', index=False)
This will create a products.csv file with the following content:
product,price,category,weight apple,0.89,fruit,13.88 carrot,1.87,vegetable,3.23
内容的提问来源于stack exchange,提问作者cinemandre




