求助:修正Python代码,生成各列含4个无重复值的DataFrame
Fixing Your DataFrame Generation Issue
Let's break down what's going wrong with your current code first:
In your nested loops, every time you iterate through a value in cal, you're overwriting the value of dict[i] with the latest calculation. By the end of the loops, each column key in your dictionary only holds the result from the last j value (13), which is why you're not getting the 4 rows of data you expect.
Here's the corrected code that will generate a DataFrame with 4 rows (one for each value in cal) and 4 columns (one for each entry in col):
import pandas as pd def newtable(): # Avoid using 'dict' as a variable name—it's a built-in Python type! data_dict = {} col = ['DAYS','VWAP','TURNOVER','DEL_QTY'] cal = [3,5,8,13] # Initialize an empty list for each column to store all 4 calculation results for column in col: data_dict[column] = [] # Loop through each calculation period first for j in cal: # Calculate the value for each column at this period and add to the list for column in col: # Get the first j rows of the target column, sum them, then divide by j column_index = final_3.columns.get_loc(column) value = final_3.iloc[:j, column_index].sum() / j data_dict[column].append(value) # Create the DataFrame, using 'cal' as the index to show which period each row corresponds to result_df = pd.DataFrame(data_dict, index=cal) print(result_df)
Key Improvements:
- Variable Name Fix: Swapped
dictfordata_dictto prevent overriding Python's built-in dictionary type. - List Initialization: Each column starts with an empty list, so we can append all 4 period results instead of overwriting a single value.
- Loop Order Adjustment: We iterate through periods first, then columns, ensuring every period's calculation is captured for each column.
- Clear Index: Using
calas the DataFrame index makes it easy to see which calculation period each row represents.
内容的提问来源于stack exchange,提问作者jacky
相关产品推荐
相关产品推荐

