python - 每次循环后重置变量
问题描述
我有多个 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_values
andy_values
不会在每次循环后重置,但会记住上一次循环的值并不断累积。需要什么命令才能在每个循环后独立/重置x_values
?y_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)
推荐阅读
- java - Java Object saving
- python - 为 DeviceCheck 创建 Json Web 令牌
- android - 如何将我的内容直播到 android 应用程序?
- c++ - Printing a map of object, which has another object as Key
- neo4j - 无法根据属性数组长度正确匹配节点
- reactjs - 在 React 中将对象数组设置为状态变量
- c++ - 为什么 CWE 认为 rand() 具有潜在危险
- apache-kafka - Kafka JMX 在一个代理中获取主题的分区
- bash - Returning from a second function in a sourced script
- mongodb - 如何从 pymongo 的数组中更新嵌入文档的字段?