I have a pandas df with multiple variables, that I want to compute the mean for. The columns are named with the variable name as prefix and the variable level as suffix. Actually, I got a lot of variables with 30 levels each, but with 2 levels and 2 variables it would look like this:
[index, oneVariable_s1, oneVariable_s2, otherVariable_s1, otherVariable_s2]
data could be generated this way:
data = [{'index':'p001', 'oneVariable_s1': 1, 'oneVariable_s2': 2, 'otherVariable_s1':3, 'otherVariable_s2':6},
{'index':'p002','oneVariable_s1':10, 'oneVariable_s2': 20, 'otherVariable_s1': 30, 'otherVariable_s2':6}]
df = pd.DataFrame(data).set_index('index')
df
Is there a way to automatically compute the mean for all columns with the same variable name/ the same prefix before "_s1" to "_s30", so that I don't have to write down all variable names for computing the means? So far I've used this to compute the mean over columns:
df['oneVariable_mean'] = df.filter(like='oneVariable').mean(axis=1)
df['otherVariable_mean'] = df.filter(like='otherVariable').mean(axis=1)
This leads to the solution I'm looking for, but I need to type in all variable names.