python - 有没有一种体面的方法来计算数据框中的迭代值?
问题描述
我有两个数据框看起来像:
col1
0 1
col2
0 2
1 3
2 4
3 5
4 6
我的目标是使用 col2 中的数字填充 col1:
col1 col2
0 1 2
1 2(=1x2) 3
2 6(=2x3) 4
3 24(=6x4) 5
4 102(=24x5) 6
因此,col1 中的数字计算为上一行 col1 中的值与上一行 col2 中的值的乘积。
解决方案
如果性能很重要,我认为numba是在这里使用循环的方式:
@jit(nopython=True)
def func(a, b):
res = np.empty(a.shape)
res[0] = b
for i in range(1, a.shape[0]):
res[i] = res[i-1] * a[i-1]
return res
df2['col1'] = func(df2['col2'].values, df1.loc[0, 'col1'])
print (df2)
col2 col1
0 2 1.0
1 3 2.0
2 4 6.0
3 5 24.0
4 6 120.0
推荐阅读
- python - 数据没有出现在 HTML 上……而是显示为空
- arrays - 提交时出现分段错误
- java - 元素类型“uses-permission”必须后跟属性规范,“>”或“/>”
- time-series - ETT数据集旁边的这个数字(24、28、168、336 ...)是什么意思?
- javascript - 如何为多个域名开启拍卖和发送投标?
- python - 创建依赖于另一个列表的列表
- javascript - 无法使用 React 捕获表单提交时的复选框值
- c# - 我可以在 XAML 代码中使用 C# 后端代码中的变量更改/绑定 HorizontalOptions 的值吗?
- java - 对 ThreadLocal 操作的性能影响
- laravel - 检查 laravel 刀片组件中的 $slot 是否为空