我有以下代码,如果满足某些条件,我想在其中添加新值并向字典添加新行。然后在 text_widget 中打印字典。
def add_preprocessing_operation():
# Clear the text_widget4 before updating
text_widget4.delete('1.0', tk.END)
# Get the inputs from the user
sr_num_operation = int(input1.get())
column_name = input2.get()
# Call the check_preprocessing_operation() function
preprocessing_dict = {}
try:
check_preprocessing_operation(df, sr_num_operation, column_name, preprocessing_dict)
except ValueError as e:
# Show a pop-up message if there is an error
messagebox.showerror("Error", e)
return
# If there are any preprocessing operations in the dictionary, print them to text_widget4
if preprocessing_dict:
table = tabulate(preprocessing_dict.items(), headers=["Column Name", "Data-Preprocessing Operation"], tablefmt="grid", numalign="center", stralign="center")
text_widget4.insert(tk.END, table)
# If there are more than one row, add a newline character
if table.count('\n') > 1:
text_widget4.insert(tk.END, '\n')
def check_preprocessing_operation(df, sr_num_operation, column_name, preprocessing_dict):
if sr_num_operation not in range(1, 10) or column_name not in df.columns:
if sr_num_operation not in range(1, 10):
print("Invalid operation entered. Check list for reference!")
if column_name not in df.columns:
print("Column ", column_name, " does not exist in the DataFrame.")
return
preprocessing_operation = preprocessing_operations[sr_num_operation]
if len(preprocessing_dict) >= 10:
raise ValueError("Maximum number of preprocessing operations reached. Cannot add more operations.")
if preprocessing_operation == "Remove Rows with Null Values":
if df[column_name].isnull().values.any():
messagebox.showerror("Error", "Operation cannot be applied to column. Column does not contains null values.")
return
else:
preprocessing_dict.setdefault(column_name, []).append(preprocessing_operation)
elif preprocessing_operation in ["Replace Null Values by Mean", "Replace Null Values by Median", "Replace Null Values by Mode"]:
if df[column_name].dtype.kind not in 'fi':
messagebox.showerror("Error", "Operation cannot be applied to column. Column does not contain numeric data.")
return
else:
preprocessing_dict.setdefault(column_name, []).append(preprocessing_operation)
elif preprocessing_operation == "Perform One Hot Encoding":
if df[column_name].dtype.kind not in 'O':
messagebox.showerror("Error", "Operation cannot be applied to column. Column does not contain categorical data.")
return
else:
preprocessing_dict.setdefault(column_name, []).append(preprocessing_operation)
elif preprocessing_operation == "Perform Label Encoding":
if df[column_name].dtype.kind not in 'O':
messagebox.showerror("Error", "Operation cannot be applied to column. Column does not contain categorical data.")
return
else:
preprocessing_dict.setdefault(column_name, []).append(preprocessing_operation)
elif preprocessing_operation in ["Perform Min Max Scaling", "Perform Standardization", "Find Outliers and Remove the Rows with Outliers"]:
if df[column_name].dtype.kind not in 'fi':
messagebox.showerror("Error", "Operation cannot be applied to column. Column does not contain numeric data.")
return
else:
preprocessing_dict.setdefault(column_name, []).append(preprocessing_operation)
else:
print("Invalid operation entered.")
add_button = tk.Button(inputs_frame, text="Add", width=10, command=add_preprocessing_operation)
add_button.grid(row=2, column=0, columnspan=2, pady=5)
但是这段代码似乎覆盖了字典,而不是在行中添加值!为了概览,截图贴在下面
正如一些评论指出的那样,您总是在 preprocessing_dict = {}
中用
add_preprocessing_operation
清空字典。你应该在函数外初始化它,也许作为 global 变量。