如何计算列表子列表y列平均值及数组最后指定数量值的均值?
Hey there! Let's break down your two Python problems and fix that GDAX code issue step by step.
1. Calculating the Average of a Specific "y Column" Across All Sublists
First up, averaging values from a specific column across all your sublists. Let's assume your main list matches the sample data you shared—each sublist follows the format [timestamp, open, high, low, close, volume] (like [1521965100, 8464.99, 8470, 8464.99, 8470, 1.8307]).
If you want the average of one specific "y column" (say, the closing price at index 4) across all sublists, here's a straightforward implementation:
# Example main list with sublists matching your data format main_list = [ [1521965100, 8464.99, 8470, 8464.99, 8470, 1.8307], [1521965200, 8470, 8472.5, 8470, 8472.5, 2.104], [1521965300, 8472.5, 8475, 8472.5, 8475, 0.987] ] # Define which index corresponds to your "y column" (closing price here is index 4) y_column_index = 4 # Extract all y values and calculate the average y_values = [sublist[y_column_index] for sublist in main_list] y_average = sum(y_values) / len(y_values) print(f"Average of the y column: {y_average:.2f}")
If instead you need the average of multiple y-values within each sublist (like averaging open/high/low/close for each individual candle), adjust the code to loop through each sublist and compute its own average:
for i, sublist in enumerate(main_list): # Grab the price values (indices 1-4: open, high, low, close) sublist_y_values = sublist[1:5] sublist_avg = sum(sublist_y_values) / len(sublist_y_values) print(f"Average for sublist {i+1}: {sublist_avg:.2f}")
2. Fixing the GDAX Code to Calculate Average of Last X Values
Now let's tackle the GDAX (now Coinbase Pro) data issue. The most common pitfalls here are mixing up the API's data order and failing to handle errors properly. Here's a working version with clear explanations:
First, make sure you have the gdax library installed:
pip install gdax
Then the corrected code:
import gdax def get_last_n_price_avg(product_id="BTC-USD", count_num=5): # Initialize the public GDAX client client = gdax.PublicClient() # Fetch historic candle data (default is 1-minute intervals, max 200 candles) historic_rates = client.get_product_historic_rates(product_id) # Handle API errors (e.g., rate limits, invalid product IDs) if isinstance(historic_rates, dict) and "message" in historic_rates: raise Exception(f"API Error: {historic_rates['message']}") # Critical note: GDAX returns candles in **NEWEST TO OLDEST** order! # So to get the latest `count_num` values, take the first `count_num` entries # If you need the oldest `count_num` values, use historic_rates[-count_num:] instead latest_n_candles = historic_rates[:count_num] # Pick your target column (matches your sample data: 1=open, 2=high, 3=low, 4=close, 5=volume) target_column = 4 # Using closing prices for this example # Extract the values and compute the average target_values = [candle[target_column] for candle in latest_n_candles] average = sum(target_values) / len(target_values) return average # Test the function try: avg = get_last_n_price_avg(count_num=5) print(f"Average of the last 5 BTC-USD closing prices: {avg:.2f}") except Exception as e: print(f"Oops, something went wrong: {e}")
Common Issues Fixed Here:
- Data Order Confusion: GDAX doesn't return candles in chronological (oldest to newest) order—newest entries come first. This is the #1 reason code for this task breaks!
- Error Handling: The API will return a dictionary with an error message if you hit rate limits or use an invalid product ID, so we check for that before processing.
- Column Index Clarity: Explicitly define which column you want to average, so you don't accidentally use the wrong value (like volume instead of price).
内容的提问来源于stack exchange,提问作者Muema

