【发布时间】:2021-01-13 14:27:23
【问题描述】:
我发现这两个伪代码脚本会产生不同的结果。
脚本 1:
# Load dataframe
Df_1 = read_csv(path to file.csv)
# Start iteration through list of dates
For date in range(250):
Df_1 = Function_that_calculates_stuff(Df_1)
# Grab data I’m interested in and save to text file
row = pd.DataFrame([[str(Df_1.iloc[1,1]), ]])
Txt_file = Txt_file.append(row, ignore_index = True)
# After loop, save dataframes
Df_1.to_csv(path to file.csv)
脚本 2:
For number in range(250):
For date in range(1):
# Load dataframe
Df_1 = read_csv(path to file.csv)
Df_1 = Function_that_calculates_stuff(Df_1)
# Grab data I’m interested in and save to text file
row = pd.DataFrame([[str(Df_1.iloc[1,1]), ]])
Txt_file = Txt_file.append(row, ignore_index = True)
Df_1.to_csv(path to file.csv)
我很困惑为什么会这样。我曾尝试一次一行地浏览代码,但找不到任何可以解释这一点的东西。
嵌套循环可以改变加载或保存在其中的数据吗?
有没有办法创建一种大坝来防止不需要的数据“泄漏”到循环的开头。
【问题讨论】:
-
这些操作方式不同,在第一个示例中,您打开文件一次并加载数据。然后,您将遍历将结果重新分配给 DF_1 的行,基本上就像过滤样式一样。所以在循环的每一次迭代中,都会根据上一次循环作用于DF_1中的数据。但是,在第二个示例中,您始终使用从文件加载的数据的新副本开始每个循环,而不是从上一个循环中剩余的数据。所以这些可能会非常不同。
标签: python-3.x for-loop nested-loops