gpt4 book ai didi

python - 向量与向量相乘,按标量 - numpy

转载 作者:行者123 更新时间:2023-12-01 02:03:37 36 4
gpt4 key购买 nike

是否可以进行向量化计算,其中一个向量中的每一列都被视为标量?

假设你有两个 numpy 数组:

a = np.array([(True, False),
(True, True),
(False, True),
(True, False),
(True, True),
(False, True),
(True, True)
])

b = np.array([[1, 3, 8, 3, 8, 3, 8],
[4, 8, 6, 8, 6, 8, 6],
[5, 9, 4, 9, 4, 9, 4],
[6, 2, 3, 2, 3, 2, 3],
[7, 4, 1, 4, 1, 4, 1],
[8, 9, 9, 9, 9, 9, 9],
[9, 1, 1, 1, 1, 1, 1]])

并且想要将a的每一列乘以整个向量b,对其进行求和并将其返回为a (或到 dataframe)。这可以矢量化完成吗(没有 for 循环)?

df = pd.DataFrame(np.zeros_like(a))

for column in range(a.shape[1]):
scalar_of_a = a[:, column][:, None]
vector_of_a_b = scalar_of_a*b
df.loc[:, column] = vector_of_a_b.sum(axis=0)[:, None]

最佳答案

使用矩阵乘法 -

df = pd.DataFrame(b.T.dot(a)) # or pd.DataFrame(a.T.dot(b).T)

使用np.einsum -

df = pd.DataFrame(np.einsum('ij,il->lj',a,b))

关于python - 向量与向量相乘,按标量 - numpy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49297298/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com