将Pandas DataFrame转换为嵌套JSON且不改变数据结构
Convert Pandas DataFrame to Nested JSON Structure
Got it, let's walk through how to turn your DataFrame into that specific nested JSON format you need. Here are two straightforward approaches—one using row iteration (great for clarity) and a more concise Pandas-native method.
Approach 1: Iterate Over Rows (Easy to Follow)
This method explicitly loops through each row of your DataFrame, building the nested structure step by step:
import pandas as pd import json # Your original DataFrame df = pd.DataFrame( [ ['2016-04-30T20:02:25.693Z', 'vmPowerOn', 'vmName'], ['2016-04-07T22:35:41.145Z','vmPowerOff','hostName'] ], columns=['date', 'event', 'object'] ) # Build the list of data entries with nested details data_entries = [] for _, row in df.iterrows(): entry = { "date": row['date'], "details": { "event": row['event'], "object": row['object'] } } data_entries.append(entry) # Construct the final JSON structure final_output = { "name": "Alarm/Error", "data": data_entries } # Print formatted JSON print(json.dumps(final_output, indent=2))
Approach 2: Pandas apply (Concise & Efficient)
If you prefer a more compact solution, use Pandas' apply function to process rows in one go:
import pandas as pd import json df = pd.DataFrame( [ ['2016-04-30T20:02:25.693Z', 'vmPowerOn', 'vmName'], ['2016-04-07T22:35:41.145Z','vmPowerOff','hostName'] ], columns=['date', 'event', 'object'] ) # Use apply to create nested entries, then convert to list data_entries = df.apply( lambda row: { "date": row['date'], "details": {"event": row['event'], "object": row['object']} }, axis=1 # Process rows instead of columns ).tolist() final_output = {"name": "Alarm/Error", "data": data_entries} print(json.dumps(final_output, indent=2))
What Both Methods Do:
- Row Processing: Each row is transformed into a dictionary where
datestays at the top level, andevent/objectare nested underdetails. - Structure Assembly: All processed rows are collected into a list, which is then wrapped into the final JSON object with the
namekey. - Formatting:
json.dumps(..., indent=2)ensures the output is pretty-printed to match your desired format.
Either approach will produce exactly the nested JSON you're looking for.
内容的提问来源于stack exchange,提问作者OverflowingTheGlass
相关产品推荐
相关产品推荐

