how to take each 12 rows and aggregate them in pandas in python

To take each 12 rows and aggregate them into a single row, you can use the groupby function in pandas.

First, you can create a new column using integer division to identify which group each row belongs to. Then you can use groupby to group by this new column, and then aggregate each group using a custom aggregation function that combines the values of all columns for each row.

Here's an example code snippet:

main.py
import pandas as pd

# create sample data frame
df = pd.DataFrame({
    'value': range(1, 101)
})

# create new column to identify which group each row belongs to
df['group'] = (df.index - 1) // 12

# define custom aggregation function
def aggregate(group):
    return pd.Series({
        'sum_value': group['value'].sum(),
        'mean_value': group['value'].mean()
    })

# group by 'group' column and aggregate using custom function
result = df.groupby('group').apply(aggregate)

print(result)
499 chars
22 lines

This will output a data frame with two columns: sum_value and mean_value, where each row represents the sum and mean of the value column for each group of 12 rows in the original data frame.

related categories

gistlibby LogSnag