【问题标题】:Reset variables after each loop每次循环后重置变量
【发布时间】:2020-10-01 16:52:53
【问题描述】:

我有多个包含两列值的 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_valuesy_values 在每次循环后不会被重置,但会记住上一次循环的值并不断累积。需要什么命令才能使x_valuesy_values 在每次循环后独立/重置?

非常感谢。

【问题讨论】:

  • 是什么让您认为x_valuesy_values 没有被重置?你能创建一个minimal reproducible example 来演示这个问题吗?
  • @0x5453我发现所有以前的csv文件中的数据都将与现在的文件一起绘制。
  • @0x5453 谢谢。我在那里找到了解决方案。只需在plt.savefig(filepath+".png") 之后添加plt.close()

标签: python loops variables reset


【解决方案1】:
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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-15
    • 2018-10-11
    • 1970-01-01
    • 2020-01-05
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    • 1970-01-01
    相关资源
    最近更新 更多