diff() function is used to obtain the discrete difference in the element of a DataFrame compared to another element of the same DataFrame.
diff() function has the following syntax:
diff() function takes the following parameter values:
periods: This takes an
intwhich represents the number of rows or columns to shift for calculating the difference.
axis: This represents the name for the row ( designated as
'index') or the column (designated as
Note: Here, Axis represents the row and column of the DataFrame. Axis with a value of
0indicate the axes running vertically downwards across a row, while a value of
1indicates the axes running horizontally across a column.
diff() function returns a DataFrame holding the first differences of the elements of the DataFrame.
Let's look at the code below:
# A code to illustrate the diff() function in Pandas # importing the pandas library import pandas as pd # creating a dataframe df = pd.DataFrame([[5,10,4,15,3], [1,7,5,9,0.5], [3,11,13,14,12]], columns=list('ABCDE')) # printing the dataframe print(df) # obtaining the differences vertically across rows print(df.diff(axis="index")) # obtaining the ifferences horizontally over columns print(df.diff(axis="columns"))
diff()function to obtain the differences in values of the elements of the DataFrame running downwards across the rows (axis
0). We print the result to the console.
diff()function to obtain the differences in values of the elements of the DataFrame running horizontally across columns (axis
1). We print the result to the console.
View all Courses