You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用@执行Pandas DataFrame与Series矩阵乘法时出现对齐错误求解

问题原因与解决方案

问题出在索引对齐不匹配:

  • DataFrame c 的列名是 s1、s2、s3
  • Series x 的默认索引是 0、1、2

Pandas 的 @ 矩阵乘法会严格按照索引/列名进行对齐,而非位置匹配。两者索引无重叠,导致无法完成矩阵乘法,抛出 ValueError: matrices are not aligned。

解决方法

方法1:统一索引与列名

修改 x 的索引,使其与 c 的列名一致:

import pandas as pd

c = pd.DataFrame({
    "s1":[.04, .018, .0064],
    "s2":[.018, .0225, .0084],
    "s3":[.0064, .0084, .0064],
})
x = pd.Series([0,0,0], index=['s1','s2','s3'], copy=False)
result = x @ c @ x
print(result)  # 输出 0.0

方法2:转为NumPy数组运算

如果不需要索引对齐,直接使用底层NumPy数组按位置运算:

import pandas as pd

c = pd.DataFrame({
    "s1":[.04, .018, .0064],
    "s2":[.018, .0225, .0084],
    "s3":[.0064, .0084, .0064],
})
x = pd.Series([0,0,0], copy=False)
result = x.values @ c.values @ x.values
print(result)  # 输出 0.0

内容的提问来源于stack exchange,提问作者324

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 19:50:22