python - Subtract each row in dataframe by one preceding it -


i have dataframe so:

day 123 126 210 230 

and want create new column subtracts each row 1 preceding it. have tried this:

df['diff']=df.set_index('day').diff() 

but doesn't seem correct.

my desired output is:

day   diff 123   0 126   3 210   84 230   20  

you don't need set day index that:

in [55]: df.day.diff().fillna(0) out[55]: 0     0.0 1     3.0 2    84.0 3    20.0 name: day, dtype: float64 

or if have 1 column:

in [56]: df.diff() out[56]:     day 0   nan 1   3.0 2  84.0 3  20.0 

if need integers:

in [58]: df.diff().fillna(0).astype(int) out[58]:    day 0    0 1    3 2   84 3   20 

Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -