search
Search
Login
Unlock 100+ guides
menu
menu
web
search toc
close
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
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

Pandas DataFrame | diff method

schedule Aug 11, 2023
Last updated
local_offer
PythonPandas
Tags
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!

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

0 or "index"

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

1 or "columns"

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

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.

robocat
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
thumb_up
0
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!