jtanman
jtanman

Reputation: 684

Grouped By, Weighted, Column Averages in Pandas

So I have two value columns and two weight columns in a Pandas DataFrame, and I want to generate a third column that is the grouped by, weighted, average of those two columns.

So for:

df = pd.DataFrame({'category':['a','a','b','b'],
  'var1':np.random.randint(0,100,4),
  'var2':np.random.randint(0,100,4),
  'weights1':np.random.random(4),
  'weights2':np.random.random(4)})
df
  category  var1  var2  weights1  weights2
0        a    84    45  0.955234  0.729862
1        a    49     5  0.225470  0.159662
2        b    77    95  0.957212  0.991960
3        b    27    65  0.491877  0.195680

I'd want to accomplish:

df
  category  var1  var2  weights1  weights2    average
0        a    84    45  0.955234  0.729862  67.108023
1        a    49     5  0.225470  0.159662  30.759124
2        b    77    95  0.957212  0.991960  86.160443
3        b    27    65  0.491877  0.195680  37.814851

I've already accomplished this using just arithmetic operators like this:

df['average'] = df.groupby('category', group_keys=False) \
  .apply(lambda g: (g.weights1 * g.var1 + g.weights2 * g.var2) / (g.weights1 + g.weights2))

But I want to generalize it to using numpy.average, so I could for example take the weighted average of 3 columns or more.

I'm trying something like this, but it doesn't seem to work:

df['average'] = df.groupby('category', group_keys=False) \
  .apply(lambda g: np.average([g.var1, g.var2], axis=0, weights=[g.weights1, g.weights2]))

returning

TypeError: incompatible index of inserted column with frame index

Can anyone help me do this?

Upvotes: 5

Views: 295

Answers (3)

BENY
BENY

Reputation: 323226

I don't even think you need groupby here. Notice, this matches the output with apply + lambda.

Try this:

col=df.drop('category',1)
s=col.groupby(col.columns.str.findall(r'\d+').str[0],axis=1).prod().sum(1)
s/df.filter(like='weight').sum(1)
Out[33]: 
0    67.108014
1    30.759168
2    86.160444
3    37.814871
dtype: float64

Upvotes: 4

danielR9
danielR9

Reputation: 455

Since you have one value in average column for every row in the df, you don't really need to groupby. You just need a dynamic way of computing the average for a variable number of 'varXXX' columns.

The answer below relies on the same number of 'var' columns and 'weights' columns, with a consistent naming pattern, as it constructs the column name string

df = pd.DataFrame({'category': ['a', 'a', 'b', 'b'],
                   'var1': np.random.randint(0, 100, 4),
                   'var2': np.random.randint(0, 100, 4),
                   'var3': np.random.randint(0, 100, 4),
                   'weights1': np.random.random(4),
                   'weights2': np.random.random(4),
                   'weights3': np.random.random(4)
                   })

n_cols = len([1 for i in df.columns if i[:3] == 'var'])

def weighted_av_func(x):
    numerator = 0
    denominator = 0
    for i in range(1, n_cols + 1):
        numerator += x['var{}'.format(i)] * x['weights{}'.format(i)]
        denominator += x['weights{}'.format(i)]
    return numerator / denominator

df['average'] = df.apply(weighted_av_func, axis=1)

print(df)

  category  var1  var2  var3  weights1  weights2  weights3    average
0        a    53    58     2  0.101798  0.073881  0.919632  10.517238
1        a    52     0    26  0.073988  0.816425  0.888792  15.150578
2        b    30    78    46  0.641875  0.029402  0.370237  37.042735
3        b    36    72    92  0.186941  0.663270  0.774427  77.391136

Edit: If you want to use np.average, and can guarantee the ordering of var columns and weights columns in your dataframe, then you could do this:

df['np_average'] = df.apply(
lambda x: np.average(a=x[1:1 + n_cols], 
                     weights=x[n_cols + 1:2 * n_cols + 1]), 
                     axis=1)

Upvotes: 0

Edeki Okoh
Edeki Okoh

Reputation: 1834

This is one approach:

import numpy as np
import pandas as pd

df = pd.DataFrame({'category': ['a', 'a', 'b', 'b'],
                   'var1': np.random.randint(0, 100, 4),
                   'var2': np.random.randint(0, 100, 4),
                   'weights1': np.random.random(4),
                   'weights2': np.random.random(4)})

df_averages = df[df.columns.difference(['category', 'var1', 'var2'])]

Output:

    weights1    weights2
0   0.002812    0.483088
1   0.159774    0.818346
2   0.285366    0.586706
3   0.427240    0.428667

df_averages['Average'] = df_averages.mean(axis=1)

Output:

    weights1    weights2    Average
0   0.002812    0.483088    0.242950
1   0.159774    0.818346    0.489060
2   0.285366    0.586706    0.436036
3   0.427240    0.428667    0.427954

df['Averages'] = df_averages['Average'].astype(float)

Output:

  category  var1    var2    weights1    weights2    Averages
0   a        60      22     0.002812    0.483088    0.242950
1   a        66      63     0.159774    0.818346    0.489060
2   b        18      10     0.285366    0.586706    0.436036
3   b        68      32     0.427240    0.428667    0.427954

Essentially remove the non weighted columns from the dataframe and move the weighted columns to a new one. Then you can apply the mean across the rows of that dataframe and merge it back in since the index will till be the same.

Upvotes: 0

Related Questions