Python 列表列表的乘法
假设我有一个两行13列的数据帧。 我使用了df.itertuples并形成了两个列表作为输出Python 列表列表的乘法,python,pandas,numpy,array-broadcasting,Python,Pandas,Numpy,Array Broadcasting,假设我有一个两行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, 测试y=[21,24] 我也试
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,
测试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。
或者有没有比这更简单的方法,因为你标记了熊猫
由于已经将列表转换为列表,因此可以使用numpy 输出:
[[ 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]
您可以对计算乘法的数据帧应用函数:
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
谢谢你的帮助谢谢你的帮助,但是我需要一个不同的格式
sum_ans=[np.sum(x) for x in ans]
#[357, 402, 447, 492, 537, 582, 627, 672, 717, 762, 807, 852, 897]
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