Home > Net >  Subtracting Entries in a Pandas Dataframe and storing in new column
Subtracting Entries in a Pandas Dataframe and storing in new column

Time:08-09

I have a column of data in a dataframe in which I am trying to subtract the first entry from the next entry and store that value in the same dataframe.

           ts  diff  
0  1659990211   187  
1  1659990230   187  
2  1659990234   187  
3  1659990252   187  
4  1659992922   187  
5  1659993109   187 

For example: I want the 'diff' column to store the difference between the 1-0, 2-1, 3-2, and so on from the 'ts' column.

I have tried used various combinations of 'append' but cant seem to get anything to work. Currently it is only storing the first value calculated (187). In python:

for i in np.arange(len(db)-1):
#print(res['ts'][i 1])
  db['diff'] = db['ts'][i 1] - db['ts'][i]
 #db['diff'] = db['diff'].append(db['ts'][i 1] - db['ts'][i]) #doesnt work.

Any help would be greatly appreciated.

CodePudding user response:

Pandas knows how to do this: diff and shift:

df['diff'] = df['ts'].diff().shift(-1)

Output:

           ts    diff
0  1659990211    19.0
1  1659990230     4.0
2  1659990234    18.0
3  1659990252  2670.0
4  1659992922   187.0
5  1659993109     NaN
  • Related