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

如何使用Python将指定嵌套JSON转换为Pandas DataFrame?

Solution to Convert JSON to Pandas DataFrame

Got it, let's break down how to transform your JSON data into the exact Pandas DataFrame you want, including handling the date formatting to remove leading zeros in the month:

Step-by-Step Implementation

1. Import Required Libraries

We'll only need pandas for creating the DataFrame—we can use basic string manipulation to format the date without extra dependencies.

2. Process the JSON Data

Iterate over each transaction in the TxnArray, extract the values (ignoring the inner keys like "0" and "1"), and adjust the date string to match your desired format.

3. Create the Final DataFrame

Convert the processed list of transactions into a Pandas DataFrame with the correct columns and index.

Full Code Example

import pandas as pd

# Your input JSON data as a Python dictionary
input_data = {
    "status": "success",
    "message": "Transactions Details",
    "TxnArray": [
        {"transactionAmount": {"0": 3500}, "createdAt": {"0": "17/04/2020"}},
        {"transactionAmount": {"1": 4500}, "createdAt": {"1": "19/04/2020"}}
    ]
}

# Process each transaction entry
processed_transactions = []
for txn in input_data["TxnArray"]:
    # Extract transaction amount (grab the only value from the inner dict)
    amount = next(iter(txn["transactionAmount"].values()))
    
    # Extract and format date to remove leading zero in month
    date_components = next(iter(txn["createdAt"].values())).split("/")
    formatted_date = f"{date_components[0]}/{int(date_components[1])}/{date_components[2]}"
    
    # Add to our processed list
    processed_transactions.append({
        "transactionAmount": amount,
        "createdAt": formatted_date
    })

# Convert to Pandas DataFrame
result_df = pd.DataFrame(processed_transactions)

# Print the final result
print(result_df)

Output

Running this code will produce exactly the DataFrame you requested:

transactionAmount  createdAt
0               3500  17/4/2020
1               4500  19/4/2020

Key Details

  • Extracting Values: next(iter(dict.values())) lets us pull the only value from each inner dictionary (like {"0": 3500}) without needing to reference the specific key.
  • Date Formatting: Splitting the date string into parts, converting the month to an integer (which strips leading zeros), then reconstructing the string gives us the clean date format you want.
  • DataFrame Setup: Passing the list of processed dictionaries to pd.DataFrame() automatically sets the correct column names and sequential index.

内容的提问来源于stack exchange,提问作者Pritesh Choksi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 18:17:34