python - 有没有办法在 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]
解决此问题的最有效方法是什么?
解决方案
你好,万能先生。你的意思是这样的吗?
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
推荐阅读
- express - NestJS - 如何使用 TypeOrm 正确更新
- javascript - 我如何在反应 js 中渲染 Mathjax 表达式,我使用的是 mathjax.org?
- laravel - laravel 多级关系急切加载尝试从子模型重新访问父模型的问题
- winapi - 更改平面滚动条的颜色(FlatSB_SetScrollProp 函数中的自定义调色板)
- postgresql - 这是什么“错误:不明确的列引用错误”?
- django - 如何聚合如果
- reactjs - 使用 componentDidMount 中的 setInterval 函数调用反应测试组件
- java - 我们如何将 File 对象从第二个活动传递到主要活动,然后将该对象转换为 uri?
- android - Jetpack Compose - 居中文本
- java - java中是否有替代java.lang.String.format()来使用通用占位符