Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to diff int64's with pandas.diff

Tags:

python

pandas

>>> pd.DataFrame([3,4,5], dtype='int64').diff()
     0
0  NaN
1  1.0
2  1.0

I would have hoped to not convert datatypes two times, is it possible?

like image 662
Jonas Byström Avatar asked Feb 18 '26 04:02

Jonas Byström


1 Answers

Yes, if you need to, you can use np.diff -

numpy.diff(a, n=1, axis=-1)

Calculate the n-th discrete difference along given axis.

The first difference is given by out[n] = a[n+1] - a[n] along the given axis, higher differences are calculated by using diff recursively.

>>> df
   A  B
0  1  4
1  2  5
2  3  6

>>> np.diff(df.values, axis=0)
array([[1, 1],
       [1, 1]])

# or as in your example:
>>> np.diff(pd.DataFrame([3,4,5], dtype='int64')[0])
array([1, 1], dtype=int64)

Note that you cannot assign this back to the original dataframe without introducing NaNs, and NaNs are of float type, meaning your result will automatically be coerced to floats.

like image 114
cs95 Avatar answered Feb 19 '26 17:02

cs95



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!