首页 > 解决方案 > 列表列表的乘法

问题描述

假设我有一个两行 13 列的数据框。我使用了 df.itertuples() 并形成了两个列表作为输出

for row in test.itertuples(index = False):
    a = np.asarray(row)
    print(a)

让我们假设上述循环的输出是

Output : [1,2,3,4,5,6,7,8,9,10,11,12,13]
[14,15,16,17,18,19,20,21,22,23,24,25,26]

我还有一个形状为 (2,) test_y = [21,24] 的列表

我也试过

a = test.values.tolist()
output : array([[1,2,3,4,5,6,7,8,9,10,11,12,13],
[14,15,16,17,18,19,20,21,22,23,24,25,26]])

这形成列表列表,然后将 test_y 乘以 a 会导致错误

error :operands could not be broadcast together with shapes (2,13) (2,)

目标是将列表 [1,2,3....] 与 21 相乘,另一个与 24 相乘。或者有没有比这更简单的方法

标签: pythonpandasnumpyarray-broadcasting

解决方案


由于您已经转换a为列表,因此可以使用numpy

import numpy as np
np.transpose(np.multiply(np.transpose(a),test_y))

输出:

[[ 21  42  63  84 105 126 147 168 189 210 231 252 273] 
 [336 360 384 408 432 456 480 504 528 552 576 600 624]]

如果您需要对元素求和(即 21+336、42+360 等),则不需要转置。

ans=np.multiply(np.transpose(a),test_y)

[[ 21 336]
 [ 42 360]
 [ 63 384]
 and so on...]

不只是将这些单独的列表中的每一个相加

sum_ans=[np.sum(x) for x in ans]
#[357, 402, 447, 492, 537, 582, 627, 672, 717, 762, 807, 852, 897]

推荐阅读