首页 > 解决方案 > 每次循环后重置变量

问题描述

我有多个 csv 文件,其中包含两列值,如下所示:

在此处输入图像描述

我使用以下 python 代码来计算 R2 值并绘制这些数据。

import numpy as np
import pandas as pd
import glob
import matplotlib.pyplot as plt

for filepath in glob.iglob(r'*.csv'):
    print(filepath)
    df = pd.read_csv(filepath)
    x_values = df["LMP"]
    y_values = df["LMP_old"]

    correlation_matrix = np.corrcoef(x_values, y_values)
    correlation_xy = correlation_matrix[0,1]
    r_squared = correlation_xy**2
    plt.scatter(x_values,y_values)
    plt.xlabel('Predicted LMP')
    plt.ylabel("Actual LMP")
    plt.title(r_squared)
    plt.xlim(20000, 26000)
    plt.ylim(20000, 26000)
    x = np.linspace(20000, 26000)
    plt.plot(x, x, linestyle='solid')
    plt.grid(True)
    plt.savefig(filepath+".png")
    print(r_squared)
    with open(filepath+".txt", "w") as text_file:
         print(f"{r_squared}", file=text_file)

但我发现x_valuesandy_values不会在每次循环后重置,但会记住上一次循环的值并不断累积。需要什么命令才能在每个循环后独立/重置x_valuesy_values

非常感谢。

标签: pythonloopsvariablesreset

解决方案


import numpy as np
import pandas as pd
import glob
import matplotlib.pyplot as plt

for filepath in glob.iglob(r'*.csv'):
    print(filepath)
    df = pd.read_csv(filepath)
    x_values = df["LMP"]
    y_values = df["LMP_old"]

    correlation_matrix = np.corrcoef(x_values, y_values)
    correlation_xy = correlation_matrix[0,1]
    r_squared = correlation_xy**2
    plt.scatter(x_values,y_values)
    plt.xlabel('Predicted LMP')
    plt.ylabel("Actual LMP")
    plt.title(r_squared)
    plt.xlim(20000, 26000)
    plt.ylim(20000, 26000)
    x = np.linspace(20000, 26000)
    plt.plot(x, x, linestyle='solid')
    plt.grid(True)
    plt.savefig(filepath+".png")
    
    plt.close()  # Adding this code solves the issue.

    print(r_squared)
    with open(filepath+".txt", "w") as text_file:
         print(f"{r_squared}", file=text_file)

推荐阅读