1

I have a data frame which consists of the following information.

STATE         VOLTS
Discharge     2.31725         
Discharge     2.31714         
Rest          2.34857        
Rest          2.38084         
Rest          2.38182        
Rest          2.38222        
Rest          2.38651        
Rest          2.38643        
Rest          2.38647        
Rest          2.38651        
Rest          2.38647        
Discharge     2.32013       
Discharge     2.31926        

What I would like to do is have my script go through the 'State' column and if it sees a change from 'Discharge' to 'Rest' it should perform the math operation: 2.34857 - 2.31714 = 0.03143 and store that value in a new data frame.

However, when going down the 'State' column, if it sees 'Rest' to 'Discharge' it should only store the the 'Volts' associated with the 'Rest' value. In this case, 2.38647. Ideally this value should also be stored in the same data frame as the previous value.

encer
  • 55
  • 6
  • Does this answer your question? [Pandas dataframe: Find location where value changes from x to y](https://stackoverflow.com/questions/53234779/pandas-dataframe-find-location-where-value-changes-from-x-to-y) – RichieV Aug 29 '20 at 02:50

1 Answers1

1

define a condition that, when true, returns the value as a new column named value:

row_cond = (df.STATE == "Rest") & (df.STATE.shift(1) == "Discharge")
new_col = "value"
df.loc[row_cond, new_col] = 2.34857 - 2.31714
anon01
  • 10,618
  • 8
  • 35
  • 58