我想看看是否有一种方法可以在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。
您可以使用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
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的模运算。