The diff()
method in pandas is used to find the difference between consecutive elements in a DataFrame or Series.
Here is an example of how to use the diff()
method in pandas:
main.py194 chars10 lines
Output:
main.py66 chars7 lines
In the above example, we create a DataFrame with column 'A' containing values [1, 3, 5, 7, 9]
. We then use the diff()
method to calculate the difference between consecutive elements in column 'A' and store the result in a new column 'diff'. The first value in the 'diff' column is NaN because there is no previous value to calculate the difference with.
Note that the diff()
method can also be used on a Series object in a similar way.
Keep in mind that the diff()
method also has optional parameters like periods
and axis
that can be used to customize the behavior of the method.
gistlibby LogSnag