【问题标题】:Is there a way to find value of a row on the bases of the last n rows in another column in a pandas Dataframe?有没有办法在 pandas Dataframe 的另一列中的最后 n 行的基础上找到一行的值?
【发布时间】:2021-05-31 09:24:08
【问题描述】:

我想为数据框的每一行找到一个新列 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]

最有效的方法是什么?

【问题讨论】:

标签: python pandas dataframe apply


【解决方案1】:

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

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

【讨论】:

  • 虽然这是正确的,但我想知道这样做是否有更少的迭代过程,也许是通过使用内置函数。另一位用户建议使用可能有效的 rolling.apply() 。还是非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-24
  • 1970-01-01
  • 2011-01-16
  • 2023-03-25
  • 1970-01-01
  • 2011-12-07
相关资源
最近更新 更多