列表列表的乘法

Multiplication of list of lists

假设我有一个两行 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 乘以一个错误

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

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

自从您标记 pandas

df=pd.DataFrame()
df['c1']= [1,2,3,4,5,6,7,8,9,10,11,12,13] 
df['c2']=[14,15,16,17,18,19,20,21,22,23,24,25,26]
df.mul([21,24])
Out[62]: 
     c1   c2
0    21  336
1    42  360
2    63  384
3    84  408
4   105  432
5   126  456
6   147  480
7   168  504
8   189  528
9   210  552
10  231  576
11  252  600
12  273  624

由于您已经将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]

您可以将函数应用于计算乘法的 DataFrame:

In: df.apply(lambda x: x*test_y)
Out: 
    0    1    2    3    4    5    6    7    8    9    10   11   12
0   21   42   63   84  105  126  147  168  189  210  231  252  273
1  336  360  384  408  432  456  480  504  528  552  576  600  624