首页 > 解决方案 > 有没有办法在 pandas Dataframe 的另一列中的最后 n 行的基础上找到一行的值?

问题描述

我想为数据框的每一行找到一个新列 dev 的值,以便:

n=100
slope=0.8
inv=3
for i in range(0,n):
   dev += math.pow(src[i] - (slope * (n - i) + inv), 2)

其中 src 是同一数据帧的一列的前 n 个值的列表。

因此,如果我的数据框是:

Index A
0     1
1     2
2     4
3     5
4     2

如果 n 的值为 3,则索引为 3 的行的 src 将是:

[4, 2, 1]

解决此问题的最有效方法是什么?

标签: pythonpandasdataframeapply

解决方案


你好,万能先生。你的意思是这样的吗?

df['dev'] = 0 ##Create a column dev with dummy values

for idx in df.index: #interating on the indexes
    dev = 0
    for i in range(n+1): #interating on the n values
        if idx >= i:
            print(idx, '-', i, '=', idx-i) #idx - i is the values above the index
            dev += np.power(df.loc[idx-i]['A'] - (slope * (n - i) + inv), 2)
        elif idx < i:
            print('No rows above.') #There will be values idx-i < 0 of which are not valid indexes for our df
            pass        
    df['dev'][idx] = dev #Here I'm setting each dev value obtained after n+1 interations,i.e., n values above

推荐阅读