What is the recommended way to compute a weighted sum of selected columns of a pandas dataframe?

拟墨画扇 提交于 2019-12-23 19:31:07

问题


For example, I would like to compute the weighted sum of columns 'a' and 'c' for the below matrix, with weights defined in the dictionary w.

df = pd.DataFrame({'a': [1,2,3], 
                   'b': [10,20,30], 
                   'c': [100,200,300],
                   'd': [1000,2000,3000]})
w = {'a': 1000., 'c': 10.}

I figured out some options myself (see below), but all look a bit complicated. Isn't there a direct pandas operation for this basic use-case? Something like df.wsum(w)?


I tried pd.DataFrame.dot, but it raises a value error:

df.dot(pd.Series(w))
# This raises an exception:
# "ValueError: matrices are not aligned"

The exception can be avoided by specifying a weight for every column, but this is not what I want.

w = {'a': 1000., 'b': 0., 'c': 10., 'd': 0. }
df.dot(pd.Series(w)) # This works

How can one compute the dot product on a subset of columns only? Alternatively, one could select the columns of interest before applying the dot operation, or exploit the fact that pandas/numpy ignores nans when computing (row-wise) sums (see below).

Here are three methods that I was able to spot out myself:

w = {'a': 1000., 'c': 10.}

# 1) Create a complete lookup W.
W = { c: 0. for c in df.columns }
W.update(w)
ret = df.dot(pd.Series(W))

# 2) Select columns of interest before applying the dot product.
ret = df[list(w.keys())].dot(pd.Series(w))

# 3) Exploit the handling of NaNs when computing the (row-wise) sum
ret = (df * pd.Series(w)).sum(axis=1)
# (df * pd.Series(w)) contains columns full of nans

Was I missing an option?


回答1:


You could use a Series as in your first example, just use reindex afterwards:

import pandas as pd

df = pd.DataFrame({'a': [1,2,3],
                   'b': [10,20,30],
                   'c': [100,200,300],
                   'd': [1000,2000,3000]})

w = {'a': 1000., 'c': 10.}
print(df.dot(pd.Series(w).reindex(df.columns, fill_value=0)))

Output

0    2000.0
1    4000.0
2    6000.0
dtype: float64



回答2:


Here's an option without having to create a pd.Series:

(df.loc[:,w.keys()] * list(w.values())).sum(axis=1)
0    2000.0
1    4000.0
2    6000.0



回答3:


Using numpy dot with values

df[list(w.keys())].values.dot(list(w.values()))
array([2000., 4000., 6000.])

Fixed your error

df.mul( pd.Series(w),1).sum(axis=1)
0    2000.0
1    4000.0
2    6000.0
dtype: float64


来源:https://stackoverflow.com/questions/53980468/what-is-the-recommended-way-to-compute-a-weighted-sum-of-selected-columns-of-a-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!