I have a dataframe with the columns "Action", "Filt" and "Val" which measure the resulting error of filtering an action. I want to calculate the mean of the error for each "Action" and "Filt". Currently, I do this by iterating through each combination of "Action" and "Filt". However, I'm afraid the slicing is taking up more time than I would like.
import pandas as pd
in_dat = [
("run", "raw", 1),
("run", "deep", 1),
("jump", "raw", 2),
("jump", "deep", 2),
("run", "raw", 2),
("run", "deep", 2),
("jump", "raw", 3),
("jump", "deep", 3)
]
all_err = pd.DataFrame(in_dat, columns=("action", "filt", "val"))
mean_vals = []
for act in tuple(all_err.action.unique()):
for filt in tuple(all_err.filt.unique()):
mean_val = all_err[(all_err.action == act) & (all_err.filt == filt)].val.mean()
mean_vals.append((act, filt, mean_val))
mean_err = pd.DataFrame(mean_vals, columns=("Action", "Filt", "Error"))
This gives the result of mean_err
being:
Action Filt Error
0 run raw 1.5
1 run deep 1.5
2 jump raw 2.5
3 jump deep 2.5
What's a faster way to do this with Pandas and getting a similar result?