如何将从Binance获取的键值对数据转换为表头-行式结构?
Hey there! Let's break down how to turn that Binance key-value data into a structured table with titles as columns and values as rows. Here's a step-by-step approach tailored to your needs:
First, make sure your raw data is properly parsed into a usable format. Binance typically returns JSON data, so if you're working with a string response, convert it into a Python dictionary (or list of dictionaries if fetching multiple data points like multiple trading pairs).
For example, if your raw response looks like this:
'{"symbol": "BTCUSDT", "price": "45000.00", "volume": "1234.56"}'
Use Python's built-in json module to parse it:
import json # Assume raw_response is the string you received from Binance raw_response = '{"symbol": "BTCUSDT", "price": "45000.00", "volume": "1234.56"}' parsed_data = json.loads(raw_response)
If you're fetching multiple entries (like a list of tickers), your parsed data will be a list of dictionaries instead.
Once your data is parsed, map all "title" keys (like symbol, price) to table columns, and each data entry to a row. The easiest way to do this is with the pandas library—it’s built for exactly this kind of structured data work.
Example with Multiple Data Entries
If you have a list of parsed Binance entries:
import pandas as pd # Sample parsed data (could come directly from your Binance API call) binance_data = [ {"symbol": "BTCUSDT", "price": "45000.00", "volume": "1234.56"}, {"symbol": "ETHUSDT", "price": "2300.00", "volume": "5678.90"}, {"symbol": "SOLUSDT", "price": "98.50", "volume": "10240.30"} ] # Convert to a DataFrame: columns = all unique "title" keys, rows = each entry df = pd.DataFrame(binance_data)
This creates a table where each column is a title from your data, and each row holds the corresponding values for a single Binance entry.
Example with a Single Data Entry
If you only have one entry, wrap it in a list to ensure it’s treated as a row:
single_entry = {"symbol": "BTCUSDT", "price": "45000.00", "volume": "1234.56"} df = pd.DataFrame([single_entry])
Now that your data is in table format, you can output it however you need:
Print the Table Directly
print(df)
This gives you a clean, readable table in your console.
Save to a CSV File (Perfect for Spreadsheets)
df.to_csv("binance_parsed_data.csv", index=False)
The index=False flag keeps the output clean by omitting pandas' default row numbers.
Save to Excel
If you need an Excel file, use to_excel (install the openpyxl library first if you haven’t):
df.to_excel("binance_parsed_data.xlsx", index=False, engine="openpyxl")
If some entries have unique titles (e.g., one entry has a high_price field others don’t), pandas will automatically fill missing values with NaN, keeping your table consistent across all rows.
内容的提问来源于stack exchange,提问作者Matthew Holland

