假设我在 Pandas 中有以下两个 DataFrame。
import Pandas as pd
data1 = {'col1': [1, 2, 3], 'col2': [4, 5, 6]}
df1 = pd.DataFrame(data1)
data2 = {'col3': [2,3]}
df2 = pd.DataFrame(data2)
我想将上面的2个DataFrame视为一个$3 imes 2$矩阵和一个$2 imes 1$矩阵,并得到data1 * data2的矩阵乘积。我尝试使用
df = df1.dot(df2)
但我收到一条错误消息
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [244], in <cell line: 1>()
----> 1 vol_df.dot(weight_df['basket_weight'].T)
File /shared/mamba/micromamba/envs/xr-sw-2209/lib/python3.9/site-packages/pandas/core/frame.py:1507, in DataFrame.dot(self, other)
1505 common = self.columns.union(other.index)
1506 if len(common) > len(self.columns) or len(common) > len(other.index):
-> 1507 raise ValueError("matrices are not aligned")
1509 left = self.reindex(columns=common, copy=False)
1510 right = other.reindex(index=common, copy=False)
ValueError: matrices are not aligned
如何修复错误?
您的索引未对齐。您可能需要使用底层 numpy 数组:
df1.dot(df2.to_numpy())
输出:
0
0 14
1 19
2 24
如果你想要乘法:
df1.mul(df2['col3'], axis=0)