乘两个数组元素方式,其中阵列中的一个具有数组作为元素 [英] Multiply two arrays element wise, where one of the arrays has arrays as elements

查看:341
本文介绍了乘两个数组元素方式,其中阵列中的一个具有数组作为元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的情况,我想聪明的乘两个数组元素,其中阵列中的一个具有数组作为元素:

 >>>导入numpy的是NP
>>>基地= np.array([100,111,])
>>> C = np.array([9,11])
>>> N0 = np.zeros(LEN(基峰))
>>> NN = 3 + N 0#这是一堆中间操作的要点
>>>格= [np.ones(i)就在我NN]
>>>基础
阵列([100,111])
>>> C
阵列([9,11])
>>> NN
阵列([3,3])
>>>格
[阵列([1,1,1]),阵列([1,1,1])]

到目前为止,一切看起来不错。 电网似乎有两个元素,每个长三个要素。我觉得我应该能够与 C

要乘以

 >>> A =格* C
回溯(最近通话最后一个):
  文件<&标准输入GT;,1号线,上述<&模块GT;
ValueError错误:操作数无法与形状(2,3)(2)被广播一起

我曾希望这不走了。该错误是有前途的。我可以做一些换位技巧和让我的结果是:


  

    

      

A =(grid.T * C).T
          回溯(最近通话最后一个):
            文件,1号线,在
          AttributeError的:'名单'对象有没有属性'T'


    
  

这是失败更espectacularly比我的预期。我以为我使用数组,但我知道我现在有一个列表。我尽我的手在一些好的老式的蛮力:

 >>> grid_mod = np.array([np.ones(3),np.ones(3)])
>>> grid_mod
阵列([1,1,1]
       [1.,1.,1。]])
>>> grid_mod * C
回溯(最近通话最后一个):
  文件<&标准输入GT;,1号线,上述<&模块GT;
ValueError错误:操作数无法与形状(2,3)(2)被广播一起

我确信会的工作!我注意到我的最后一个元素之后的多余的空间,所以我将其删除:

 >>> grid_mod2 = np.array([np.ones(3),np.ones(7)])
>>> grid_mod2
阵列([阵列([1,1,1]),阵列([1,1,1,1,1,1,1])],DTYPE =对象)
>>> grid_mod2 * C
阵列([阵列([9,9,9]),
       阵列([11,11,11,11,11,11,11])],DTYPE =对象)

这是最后一个按预期工作。

我的问题是:


  1. 如何定义电网这样的结果是数组,而不是数组列表组成的数组。

  2. 什么的这一切实际上是怎么回事?为什么在数组的末尾额外的空间给我一个完全不同的结果。

  3. 有中会对此更Python的方式?


解决方案

这两个code片产生不同的东西,虽然空间没有任何影响:

 >>> np.array([np.ones(3),np.ones(3)])
阵列([1,1,1]
       [1.,1.,1。]])

由于在列表中两个阵列具有相同的尺寸,这被转换成2行3列的单个阵列

 >>> np.array([np.ones(3),np.ones(7)])
阵列([阵列([1,1,1]),阵列([1,1,1,1,1,1,1])],DTYPE =对象)

在此情况下,数组的长度不匹配,所以numpy的创建一维数组,两个项目长,类型对象并且其中的每个对象恰巧是一个numpy的数组。

当你乘先用 C ,你想乘形状数组(2,3)与形状的阵列(2),一些numpy的不知道该怎么办。你可以得到你想要的东西,如果你重新塑造你的 C 阵列有形状(2,1),如:

 >>> grid_mod * C [:, np.newaxis]
阵列([9,9,9]
       [11,11,11])

当你乘用第二个C ,你想乘形状的两个数组(2) ,所以numpy的确实的elementwise乘法,没有任何问题。而且,由于每个阵列中的项目本身是一个数组,当您试图通过一个标量乘以它,也numpy的知道该怎么做。虽然这个工作,它是多,比previous方法要慢得多,大约为100倍10000行数组:

  C = np.random.rand(10000)
A = np.random.rand(10000,3)
B = np.empty((10000,),DTYPE =对象)
对于j中的xrange(10000):
    B〔J] = A [J]。%timeit A * C [:, np.newaxis]
10000循环,最好的3:176我们每个环路%timeit B * C
10圈,最好的3:每循环16.5毫秒

I have the following situation in which I want to multiply two arrays element wise, where one of the arrays has arrays as elements:

>>> import numpy as np
>>> base = np.array( [100., 111.,] )
>>> c = np.array( [9., 11.] )
>>> n0 = np.zeros(len(base))
>>> nn = 3 + n0     # This is the gist of a bunch of intermediate operations
>>> grid = [np.ones(i) for i in nn]
>>> base
array([ 100.,  111.])
>>> c
array([  9.,  11.])
>>> nn
array([ 3.,  3.])
>>> grid
[array([ 1.,  1.,  1.]), array([ 1.,  1.,  1.])]

So far everything looks good. grid seems to have two elements, three elements long each. I feel I should be able to multiply it with c

>>> a = grid * c
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (2,3) (2) 

That does not go as I had hoped for. The error is promising. I can do some transposition tricks and get my result:

a = (grid.T * c).T Traceback (most recent call last): File "", line 1, in AttributeError: 'list' object has no attribute 'T'

That fails more espectacularly than I expected. I thought I was working with an array, but I learn that I now have a list. I try my hand at some good old fashioned brute force:

>>> grid_mod = np.array( [np.ones(3), np.ones(3) ] )
>>> grid_mod
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.]])
>>> grid_mod * c
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (2,3) (2) 

I was sure that would work! I notice an extraneous space after my last element, so I remove it:

>>> grid_mod2 = np.array( [np.ones(3), np.ones(7)] )
>>> grid_mod2
array([array([ 1.,  1.,  1.]), array([ 1.,  1.,  1.,  1.,  1.,  1.,  1.])], dtype=object)
>>> grid_mod2 * c
array([array([ 9.,  9.,  9.]),
       array([ 11.,  11.,  11.,  11.,  11.,  11.,  11.])], dtype=object)

That last one works as expected.

My questions are:

  1. How can I define grid so that the result is an array of arrays instead of a list of arrays.
  2. What is actually going on in all of this? Why does the extra space at the end of the array give me a completely different result.
  3. Is there a more pythonic way of going about this?

解决方案

These two pieces of code produce different things, although the space has no effect:

>>> np.array([np.ones(3), np.ones(3)])
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.]])

Because both arrays in your list have the same dimension, this is converted into a single array of 2 rows and 3 columns.

>>> np.array([np.ones(3), np.ones(7)])
array([array([ 1.,  1.,  1.]), array([ 1.,  1.,  1.,  1.,  1.,  1.,  1.])], dtype=object)

In this case, the lengths of the arrays do not match, so numpy creates a 1D array, two items long, of type object and each of those objects happens to be a numpy array.

When you multiply the first with c, you are trying to multiply an array of shape (2, 3) with an array of shape (2,), something numpy does not know how to do. You could get what you want if you reshaped your c array to have shape (2, 1), e.g.

>>> grid_mod * c[:, np.newaxis]
array([[  9.,   9.,   9.],
       [ 11.,  11.,  11.]])

When you multiply the second with c, you are trying to multiply two arrays of shape (2,), so numpy does elementwise multiplication with no problems. And since each of the items of your array is itself an array, when you try to multiply it by a scalar, numpy also know how to do it. While this does work, it is much, much slower than the previous approach, about 100x for 10000 row arrays:

c = np.random.rand(10000)
a = np.random.rand(10000, 3)
b = np.empty((10000,), dtype=object)
for j in xrange(10000):
    b[j] = a[j]

%timeit a*c[:, np.newaxis]
10000 loops, best of 3: 176 us per loop

%timeit b*c
10 loops, best of 3: 16.5 ms per loop

这篇关于乘两个数组元素方式,其中阵列中的一个具有数组作为元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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