I have a situation like Pandas Group Weighted Average of Multiple Columns but where some values of one column are sometimes NaN.
That is, I am doing the following:
import pandas as pd
import numpy as np
df=pd.DataFrame({'category':['a','a','b','b'],
'var1':np.random.randint(0,100,4),
'var2':np.random.randint(0,100,4),
'weights':np.random.randint(0,10,4)})
df.loc[1,'var1']=np.nan
df
category var1 var2 weights
0 a 74.0 99 9
1 a NaN 8 4
2 b 13.0 86 2
3 b 49.0 38 7
def weighted(x, cols, w="weights"):
# Following fails when NaNs might be present:
#return pd.Series(np.average(x[cols], weights=x[w], axis=0), cols)
return pd.Series([np.nan if x.dropna(subset=[c]).empty else np.average(x.dropna(subset=[c])[c], weights =x.dropna(subset=[c])[w] ) for c in cols], cols)
df.groupby('category').apply(weighted, ['var1', 'var2'])
var1 var2
category
a 74.0 57.846154
b 23.0 8.000000
I'd like a nicer way to do this, but np.nanmean does not allow weights. np.average does not allow options to control treatment of NaNs.