python - 列表列表的乘法
问题描述
假设我有一个两行 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 相乘。或者有没有比这更简单的方法
解决方案
由于您已经转换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]
推荐阅读
- reactjs - React 中自定义属性的内联访问
- python - 我想使用 python 将 xml 文件转换为文本文件
- java - 如何从控制台测试多个输入?
- c# - DateTime.TryParse 更改实际日期值 C#
- c# - 使用 HttpClient 和 PushStreamContent 将实时音频文件发送到 REST 服务器
- excel - 如何使用动态范围将具有相同结构的不同工作簿合并为一个
- javascript - Ruby on Rails - 单击按钮时将从 Javascript 下拉列表中选择的项目传递给 Rails 控制器
- .net - 动态加载的程序集 - MVC 和 WCF 行为不同
- google-cloud-platform - GCP - 如何使用 Java 注册对象更改
- c# - 表单按钮事件和表单类继承