>>> 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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With