2017-06-19 41 views
3

例如:舍入元件以相同的索引的数量在另一个阵列

a=[[ 2.22323422 3.34342 ] 
    [ 24.324  97.56464 ]] 

round_to= [[2 1] 
      [1 3]] 

我的预期输出将是:

a_rounded= [[ 2.2 3. ] 
      [ 2. 97.6]] 

我想这样做没有切片出每个元素,并单独做。

+2

将24.324舍入到2似乎不合逻辑。 – Psidom

+0

我刚刚从我的袖子里拉出了一个例子,这就是为什么我没有注意到这一点。 –

回答

0

三个选项:

  1. 类似的东西使用与NumPy的.item列出理解。
  2. itertools.starmap
  3. np.broadcast

时序如下。 选项3似乎是迄今为止最快的路线。

from itertools import starmap 

np.random.seed(123) 
target = np.random.randn(2, 2) 
roundto = np.arange(1, 5, dtype=np.int16).reshape((2, 2)) # must be type int 

def method1(): 
    return (np.array([round(target.item(i), roundto.item(j)) 
        for i, j in zip(range(target.size), 
            range(roundto.size))]) 
            .reshape(target.shape)) 

def method2(): 
    return np.array(list(starmap(round, zip(target.flatten(), 
           roundto.flatten())))).reshape(target.shape) 

def method3(): 
    b = np.broadcast(target, roundto) 
    out = np.empty(b.shape) 
    out.flat = [round(u,v) for (u,v) in b] 
    return out 

from timeit import timeit 

timeit(method1, number=100) 
Out[50]: 0.003252145578553467 

timeit(method2, number=100) 
Out[51]: 0.002063405777064986 

timeit(method3, number=100) 
Out[52]: 0.0009481473990007316 

print('method 3 is %0.2f x faster than method 2' % 
     (timeit(method2, number=100)/timeit(method3, number=100))) 
method 3 is 2.91 x faster than method 2 
+0

我也想避免for循环,但是谢谢你的回应。在这种情况下似乎没有其他选择。 –

+0

当然可以。刚刚在这个网站上。 –

相关问题