search
Search
Join our weekly DS/ML newsletter layers DS/ML Guides
menu
menu search toc more_vert
Robocat
Guest 0reps
Thanks for the thanks!
close
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
help Ask a question
Share on Twitter
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
icon_star
Doc Search
icon_star
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Navigate to
A
A
brightness_medium
share
arrow_backShare
Twitter
Facebook

Pandas DataFrame | diff method

Programming
chevron_right
Python
chevron_right
Pandas
chevron_right
Documentation
chevron_right
DataFrame
chevron_right
Basic and Descriptive Statistics
schedule Jul 1, 2022
Last updated
local_offer PythonPandas
Tags

Pandas DataFrame.diff(~) method returns a new DataFrame where each value represents the difference between the value and the value of the previous row or column.

Parameters

1. periodslink | int | optional

If periods=3, then instead of taking the difference of the previous row/column, the difference is computed using the 3rd row/column before. Both positive and negative integers are allowed. By default, periods=1.

2. axis | int or string | optional

Whether or not the take the difference of the previous row or column:

Axis

Description

Take the difference between the previous row value in the same column.

0 or "index"

Take the difference between the previous column value in the same row.

1 or "columns"

By default, axis=0.

Return Value

A new DataFrame.

Examples

Basic usage

Consider the following DataFrame:

df = pd.DataFrame({"A":[3,4,6],"B":[1,4,9]})
df
A B
0 3 1
1 4 4
2 6 9

Computing the difference between each value and its previous value in the same column:

df.diff()
A B
0 NaN NaN
1 1.0 3.0
2 2.0 5.0

Notice how the first row is NaN - this is because there is no previous row with which to compute the difference.

Specifying periods

To compute the difference between each value and the value that is 2 rows prior in the same column:

df.diff(periods=2)
A B
0 NaN NaN
1 NaN NaN
2 3.0 8.0

periods also accepts a negative integer:

df.diff(periods=-1)
A B
0 -1.0 -3.0
1 -2.0 -5.0
2 NaN NaN

Here, instead of taking the difference between the previous value, we take the difference between the next value.

mail
Join our newsletter for updates on new DS/ML comprehensive guides (spam-free)
robocat
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
Ask a question or leave a feedback...
0
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!