如果 x 是 pandas 系列,为什么点积 x@A 不起作用?

Why doesn't dot product x@A work if x is a pandas Series?

x@A returns 错误 ValueError: matrices are not aligned 尽管它们显然都满足点积乘法的要求,具有相同的外部维度,5.

x.values @ A 有效,返回预期的标量,仅仅是因为 x 已从 pandas 系列更改为 numpy 数组

为什么点符号 @ 对 pandas 如此挑剔?

参见 documentation:

In addition, the column names of DataFrame and the index of other must contain the same values, as they will be aligned prior to the multiplication.

因此错误与维度无关,而是与索引不匹配有关。请参阅以下示例:

import pandas as pd

df = pd.DataFrame([[1,2],[3,4]], columns=list('ab'))
s = pd.Series([5,6])

# df @ s                                      # --> doesn't work
print(df.values @ s)                          # --> works because no column names involved
print(df.rename({'a':0, 'b':1}, axis=1) @ s)  # --> works because indices match

或反过来

df = pd.DataFrame([[1,2],[3,4]], index=list('ab'))
s = pd.Series([5,6])

# s @ df                             # --> doesn't work
print(s @ df.values)                 # --> works because no column names involved
print(s @ df.reset_index(drop=True)) # --> works because indices match