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

标签 python pandas numpy vector dot-product

  • A 是一个 5x5 方阵pandas DataFrame
  • x 是一个 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/

相关文章:

python - Airflow : pass parameter from python function to MySQL Operator

python - 在 Pandas 的 GroupBy 中检查负滚动窗口中的条件

Python 有缺陷的直方图?

python Pandas : how to speed up exporting dataframes to csv?

numpy - 从NumPy数组中提取 block 或补丁

numpy - 如何使用 Dask.array 有效地将大型 numpy 数组发送到集群

python - 通过python脚本向apache发送http请求

python : How to find the count of empty cells in one column based on another column element wise?

python - 如何将由可打印字符组成的字符串映射到整数

python - 在数据框中应用单元函数