0

I'd like to see if there's a way to calculate something like the following on Python, is it possible?

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

In general my code is df['current_degree'] = df.apply(lambda row: row.starting_degree - row.rotation, axis = 1), but I'd like the starting degree figure to change based on ID and any previous calculations.

With each new ID the starting degree resets to 360.

maakef
  • 1
  • 1
  • What is being calculated here? Please provide a [mcve] – G. Anderson Oct 09 '19 at 21:16
  • In general my code is df['current_degree'] = df.apply(lambda row: row.starting_degree - row.rotation, axis = 1), but I'd like the starting degree figure to change based on ID and any previous calculations – maakef Oct 09 '19 at 21:21
  • Please [edit] your code into the question, as comments make code unreadable – G. Anderson Oct 09 '19 at 21:22
  • Possible duplicate of [Subtract two columns in dataframe](https://stackoverflow.com/questions/48350850/subtract-two-columns-in-dataframe) – G. Anderson Oct 09 '19 at 21:25
  • 2
    The basic question is answered in the linked duplicate, but if you need more in-depth calculations, you need to ask a more specific question with a [mcve], again, perhaps taking a look at [How to make good pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) – G. Anderson Oct 09 '19 at 21:27

1 Answers1

0

IIUC, you want to calculate the current degree given the rotation:

# 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']

You may want to do a modulo by 360 for non-negative current degree.

Quang Hoang
  • 146,074
  • 10
  • 56
  • 74