Python中数组乘法/除法的重塑
当我处理长度相同但宽度仅为一的数组时,我遇到了一个恼人的形状不匹配问题。例如:
import numpy as np
x = np.ones(80)
y = np.ones([80, 100])
x*y
ValueError: shape mismatch: objects cannot be broadcast to a single shape
简单的解决方案是 y*x.reshape(x.shape[0],1)。然而,我经常最终对数组的一列进行子集化,然后必须指定此重塑。有办法避免这种情况吗?
I'm encountering an annoying shape mismatch issue when I'm working with arrays that are the same length, but one is only width one. For example:
import numpy as np
x = np.ones(80)
y = np.ones([80, 100])
x*y
ValueError: shape mismatch: objects cannot be broadcast to a single shape
The simple solution is y*x.reshape(x.shape[0],1). However, I often end up subsetting one column of an array, and then having to designate this reshape. Is there a way to avoid this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
两种简单的方法是:
或者
Numpy 的 广播 是一个非常强大的功能,并且会自动执行您想要的操作,但它期望数组的最后一个轴(或多个轴)具有相同的形状,而不是第一个轴。因此,您需要转置 y 才能使其正常工作。
第二个选项与您正在执行的操作相同,但
-1
被视为数组大小的占位符,这会减少一些输入。Two somewhat easy ways are:
or
Numpy's broadcasting is a very powerful feature, and will do exactly what you want automatically, but it expects the last axis (or axes) of the arrays to have the same shape, not the first axes. Thus, you need to transpose
y
for it to work.The second option is the same as what you're doing, but
-1
is treated as a placeholder for the array's size, which reduces some typing.最受欢迎的方法是使用“newaxis”,即
它非常可读且高效。
The favored method is to use a "newaxis", that is
It is very readable and efficient.