添加和与另一阵列相乘的numpy的阵列的列 [英] Adding and multiplying columns of a numpy array with another array

查看:166
本文介绍了添加和与另一阵列相乘的numpy的阵列的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 2D numpy的阵列 X 和和 1D numpy的阵列

I have a 2D numpy array x and and 1D numpy array y:

import numpy as np
x = np.arange(12).reshape((4, 3))
y = np.array(([1.0,2.0,3.0,4.0])

我要乘/加列向量 y.reshape((4,1)) X 。我尝试以下内容:

y1 = y.reshape((4,1))    
y1 * x 

收益

array([[ 0., 1., 2.], 
       [ 6., 8., 10.], 
       [ 18., 21., 24.], 
       [ 36., 40., 44.]])

这就是我想要的。我还发现

which is what I wanted. I also found

array([[ 1., 2., 3.], 
       [ 5., 6., 7.], 
       [ 9., 10., 11.], 
       [ 13., 14., 15.]])

Y1 + X 。结果
我想知道,如果有更好(更有效)的方式来达到同样的事情!

with y1 + x.
I would like to know if there is a better (more efficient) way to achieve the same thing!

推荐答案

numpy的通过广播支持这一点。您code使用的广播,它是做事的最有效的方法。我通常写为:

NumPy supports this via broadcasting. Your code used broadcasting and it's the most efficient way to do things. I normally write it as:

>>> x * y[..., np.newaxis]
array([[  0.,   1.,   2.],
       [  6.,   8.,  10.],
       [ 18.,  21.,  24.],
       [ 36.,  40.,  44.]])

要看到它是等价的:

>>> z =  y[..., np.newaxis]
>>> z.shape
(4, 1)

您还可以看到numpy的不复制任何数据,它只是改变了相同的内存迭代内部

You can also see that NumPy doesn't copy any data, it just changes the iteration over the same memory internally

>>> z.base is y
True

在这里阅读更多

  • http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html
  • https://scipy-lectures.github.io/intro/numpy/operations.html#broadcasting

这篇关于添加和与另一阵列相乘的numpy的阵列的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆