基于先前值的累加和和Python上的ID?

问题描述 投票:0回答:2

我想看看是否有一种方法可以在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。

python pandas
2个回答
0
投票

您可以使用df [Columnname] .sub(df [Othercolumn])减去整列:

import pandas as pd

df = pd.DataFrame({'Rotation': [45, 55, 40, 20],
                   'Starting_degree': [450, 340, 230, 445],})

#create new column for results
result = df['Starting_degree'].sub(df['Rotation'])

df['Current_degree'] = result

print(df)

请参阅文档以获取更多信息:https://pandas.pydata.org/pandas-docs/version/0.25/reference/api/pandas.DataFrame.sub.html


0
投票

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的模运算。

© www.soinside.com 2019 - 2024. All rights reserved.