首页 > 解决方案 > 基于先前值和 Python 上的 ID 的重复总和?

问题描述

我想看看是否有一种方法可以在 Python 上计算类似以下内容,这可能吗?

ID Rotation Starting_degree Current_degree
1  40       360             320
1  55       320             265
2  70       360             290
1  15       265             250
2  20       290             270
3  30       360             330
3  60       330             270
1  25       250             225

一般来说,我的代码是df['current_degree'] = df.apply(lambda row: row.starting_degree - row.rotation, axis = 1),但我希望根据 ID 和任何先前的计算来更改起始度数。

每个新 ID 的起始度数重置为 360。

标签: pythonpandas

解决方案


IIUC,你想计算给定旋转的当前度数:

# assume that all IDs start with 360
df['Start'] = 360

# grouping by ID
groups = df.groupby("ID")

# compute the total rotation by cumsum
df['Rot_so_far'] = groups.Rotation.cumsum()

# current degree
df['Current_degree'] = df['Start'] - df['Rot_so_far']

您可能希望对非负电流度数进行 360 模运算。


推荐阅读