nor*_*ius 5 python dot-product pandas
例如,我想为下面的矩阵计算列 'a' 和 'c' 的加权和,权重在字典中定义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.}
Run Code Online (Sandbox Code Playgroud)
我自己想出了一些选项(见下文),但看起来都有些复杂。这个基本用例没有直接的熊猫操作吗?像df.wsum(w)什么?
我试过了pd.DataFrame.dot,但它引发了一个值错误:
df.dot(pd.Series(w))
# This raises an exception:
# "ValueError: matrices are not aligned"
Run Code Online (Sandbox Code Playgroud)
可以通过为每一列指定权重来避免异常,但这不是我想要的。
w = {'a': 1000., 'b': 0., 'c': 10., 'd': 0. }
df.dot(pd.Series(w)) # This works
Run Code Online (Sandbox Code Playgroud)
如何仅计算列子集上的点积?或者,可以在应用点操作之前选择感兴趣的列,或者利用 pandas/numpynan在计算(按行)总和时忽略s的事实(见下文)。
以下是我自己发现的三种方法:
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
Run Code Online (Sandbox Code Playgroud)
我错过了一个选项吗?
您可以像第一个示例一样使用 Series,然后使用 reindex:
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)))
Run Code Online (Sandbox Code Playgroud)
输出
0 2000.0
1 4000.0
2 6000.0
dtype: float64
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1847 次 |
| 最近记录: |