A
是一个 5x5 方阵pandas DataFramex
是一个 5(一维)向量 pandas 系列
x@A
返回错误 ValueError: 矩阵未对齐
,即使它们显然都满足点积乘法的要求,具有相同的外部维度 5。
而 x.values @ A
可以工作,返回预期的标量,仅仅是因为 x
已从 pandas Series 更改为 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
关于python - 如果 x 是 pandas 系列,为什么点积 x@A 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65651891/