每次循环后重置变量

问题描述

我有多个具有两列值的csv文件,如下所示:

enter image description here

我使用以下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_valuesy_values在每个循环之后都不会重置,但是会记住上一个循环的值并不断累加。需要什么命令才能使x_valuesy_values在每次循环后独立/复位?

非常感谢您。

解决方法

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)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...