如何使用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
相关产品推荐
相关产品推荐

