subtraction between two rows in python

Assuming you have a pandas DataFrame and you want to subtract one row from another, you can use the .diff() method with a specified number of periods. Here's an example:

main.py
import pandas as pd

df = pd.DataFrame({
    'A': [10, 20, 30, 40],
    'B': [5, 10, 15, 20],
})

# subtract second row from first row
result = df.diff(periods=1).iloc[1]

print(result)
186 chars
12 lines

This will output:

main.py
A    10.0
B     5.0
Name: 1, dtype: float64
44 chars
4 lines

The diff() method calculates the difference between each row and the row preceding it. We specify periods=1 to only calculate the difference between adjacent rows. We then use .iloc[1] to select the second row of the resulting DataFrame, which represents the difference between the first and second rows of the original DataFrame.

related categories

gistlibby LogSnag