I have a pandas data frame with many columns and for each column I would like to generate a new columns where the result is the percent difference of the value in relation to the mean of that column, as seen in the example below:
d = {'var1': [1, 2], 'var2': [3,4]}
df = pd.DataFrame(data=d)
df
var1 var2
0 1 3
1 2 4
result:
var1 var2 var1_avg var2_avg
0 1 3 -0.33 -0.14
1 2 4 0.33 0.14
I am aware of how to find the mean of the column and then compute the percent difference, but only for a singe column, as seen below:
df['var1_avg'] = (df.var1 - df.var1.mean()) / df.var1.mean()
However, I have 100's of columns and would like a way where I can apply this to each column and append the "_avg" to each new column name.