how to take average every two rows in pandas dataframe in python

To take the average of every two rows in a pandas DataFrame in Python, you can use the groupby() and mean() functions. Here's an example:

main.py
import pandas as pd

# Create a sample DataFrame
data = {'A': [1, 2, 3, 4, 5, 6],
        'B': [7, 8, 9, 10, 11, 12]}
df = pd.DataFrame(data)

# Group the DataFrame in pairs and calculate the mean
averages = df.groupby(df.index // 2).mean()

print(averages)
258 chars
12 lines

Output:

main.py
   A   B
0  1   7
1  3   9
2  5  11
36 chars
5 lines

In this example, we divide the index of the DataFrame by 2 using the // operator to generate groups of two rows. Then, we apply the mean() function to calculate the average within each group. The resulting DataFrame contains the average values for columns 'A' and 'B' for every two rows in the original DataFrame.

related categories

gistlibby LogSnag