The diff() function helps you find how much values change between rows or columns. It shows the difference step-by-step, making it easy to see trends or changes.
0
0
diff() for differences in Pandas
Introduction
To see daily changes in stock prices from a list of prices.
To find how much sales increased or decreased each month.
To calculate the change in temperature from one day to the next.
To analyze the difference in scores between rounds in a game.
To detect sudden jumps or drops in sensor data over time.
Syntax
Pandas
DataFrame.diff(periods=1, axis=0)
periods sets how many steps to look back for difference (default is 1).
axis=0 means difference between rows; axis=1 means difference between columns.
Examples
Finds difference between each row and the previous row (default 1 period, axis=0).
Pandas
df.diff()
Finds difference between each row and the row 2 steps before.
Pandas
df.diff(periods=2)Finds difference between each column and the previous column for each row.
Pandas
df.diff(axis=1)Sample Program
This code creates a table of sales over 5 days. Then it adds a new column showing how much sales changed from the previous day.
Pandas
import pandas as pd data = {'Day': [1, 2, 3, 4, 5], 'Sales': [100, 120, 115, 130, 125]} df = pd.DataFrame(data) # Calculate daily sales difference df['Sales_diff'] = df['Sales'].diff() print(df)
OutputSuccess
Important Notes
The first difference value is always NaN because there is no previous row to subtract from.
You can use diff() on both Series and DataFrames.
Negative values mean a decrease, positive values mean an increase.
Summary
diff() shows how values change step-by-step.
Use it to find differences between rows or columns easily.
It helps spot trends, jumps, or drops in your data.