Pandas循环调用前一行计算结果异常问题排查
递归计算行差时结果不符合预期的问题分析与解决
问题场景
尝试计算DataFrame中第i行与第i-1行的差值,预期每行结果均为[4,4,4,4],但实际输出不符合预期。
原始函数(使用iloc[i-1]):
import pandas as pd def myfunction(df): #获取表格长度用于循环: code_len = df.shape[0] print(df) #创建新的输出df dnl = df #循环中用第i行减去第i-1行 for i in range(1, code_len): print(i) dnl.iloc[i] = (df.iloc[i] - df.iloc[i-1]) #删除第一行,因为没有可减的前一行 dnl = dnl.drop(0) print(dnl) return dnl
输入DataFrame:
0 1 2 3 0 0 1 2 3 1 4 5 6 7 2 8 9 10 11 3 12 13 14 15
实际输出:
0 1 2 3 1 4 4 4 4 2 4 5 6 7 3 8 8 8 8
后续尝试使用shift()修改函数,结果依旧错误:
def myfunction(df): code_len = df.shape[0] print(df.tail()) dnl = df for i in range(1, code_len): print(i) dnl.iloc[i] = (df.iloc[i] - df.shift().iloc[i]) dnl = dnl.drop(0) print(dnl) return dnl
问题根源
核心问题是直接赋值导致的引用传递:
- 代码中
dnl = df并没有创建新的DataFrame,而是让dnl指向原df的内存地址,属于引用赋值。 - 执行
dnl.iloc[i] = ...时,实际是在修改原df的数据。 - 后续循环中,
df.iloc[i-1]已经是被修改后的值,而非原始输入的数值,导致计算结果错误。
比如i=1时,修改了dnl.iloc[1](即原df的第1行)为[4,4,4,4];当i=2时,df.iloc[1]已经不是原来的[4,5,6,7],而是被修改后的[4,4,4,4],所以计算df.iloc[2] - df.iloc[1]得到[4,5,6,7],这就是错误结果的来源。
修复方案
方案1:修正循环逻辑,使用副本避免修改原数据
将dnl = df改为dnl = df.copy(),创建原DataFrame的深副本,修改dnl时不会影响原df的数据:
import pandas as pd def myfunction(df): code_len = df.shape[0] dnl = df.copy() # 创建副本,避免修改原df for i in range(1, code_len): dnl.iloc[i] = df.iloc[i] - df.iloc[i-1] dnl = dnl.drop(0) return dnl # 测试 df = pd.DataFrame([[0,1,2,3],[4,5,6,7],[8,9,10,11],[12,13,14,15]]) print(myfunction(df))
输出结果:
0 1 2 3 1 4 4 4 4 2 4 4 4 4 3 4 4 4 4
方案2:使用pandas内置的diff()方法(推荐)
pandas提供了专门计算相邻行/列差值的diff()方法,无需手动循环,代码更简洁高效:
import pandas as pd def myfunction(df): return df.diff().dropna() # diff计算行差,dropna删除第一行空值 # 测试 df = pd.DataFrame([[0,1,2,3],[4,5,6,7],[8,9,10,11],[12,13,14,15]]) print(myfunction(df))
输出结果与预期一致,且代码更简洁。
内容的提问来源于stack exchange,提问作者ActualTurtle
相关产品推荐
相关产品推荐

