python - numpy:数组数组乘以整数数组等于数组
问题描述
有没有一种 Pythonic 的方法来计算数组z
而不使用循环?
import numpy as np
x = np.array([[1, 2, 3], [6, 7, 8]])
y = np.array([5, 8])
z = np.array([x[i] * y[i] for i in range(0, len(x))])
解决方案
你可以做:
x * np.expand_dims(y, 1)
乘以(shape 2×3)时,乘法将根据需要广播expand_dims
(shape 2×1)的结果x
。
结果:
array([[ 5, 10, 15],
[48, 56, 64]])
推荐阅读
- typescript - 打字稿,泛型函数可能返回回调函数
- javascript - 正则表达式中的有效格式问题
- typescript - amcharts 集成 SCRIPT1002 IE 11 中的语法错误
- php - 在 laravel 会话中使用它的键值忘记索引
- ubuntu - 如何在 Ubuntu 中模拟低磁盘写入速度?
- google-sheets - 如何在 Google Data Studio 或 Google Sheets 中将“-infinity”更改为今天的日期?
- javascript - 将函数标记为打字稿类型中的函数
- python - 使用从“UTF-16”编码的 csv 文件中读取的 pandas 数据帧
- java - 您如何测试反应式 mongo 存储库?
- c++ - 为了避免崩溃,此循环中的最大迭代次数是多少?