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

将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:

  1. Row Processing: Each row is transformed into a dictionary where date stays at the top level, and event/object are nested under details.
  2. Structure Assembly: All processed rows are collected into a list, which is then wrapped into the final JSON object with the name key.
  3. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:13:09