how to make differnces of multiple columsn in a dataframe in python

To make differences of multiple columns in a dataframe, we can use the pandas library’s DataFrame.diff() method. This method calculates the first difference of a DataFrame and returns a new DataFrame.

Here is an example of how to make differences of multiple columns in a dataframe:

main.py
import pandas as pd

# Creating a sample dataframe
data = {'A': [1, 2, 3, 4, 5], 'B': [10, 20, 30, 40, 50], 'C': [100, 200, 300, 400, 500]}
df = pd.DataFrame(data)

# Calculating differences
diff_df = df.diff()

# Displaying the difference dataframe
print(diff_df)
265 chars
12 lines

This will output:

main.py
     A     B      C
0  NaN   NaN    NaN
1  1.0  10.0  100.0
2  1.0  10.0  100.0
3  1.0  10.0  100.0
4  1.0  10.0  100.0
120 chars
7 lines

In the output dataframe, you can see that the first row contains NaN because there is no previous row to calculate the difference with. The remaining rows show the differences between the corresponding values of the dataframe.

related categories

gistlibby LogSnag