3
a=[[ 2.22323422 3.34342 ]
[ 24.324 97.56464 ]]
round_to= [[2 1]
[1 3]]
我的預期輸出將是:
a_rounded= [[ 2.2 3. ]
[ 2. 97.6]]
我想這樣做沒有切片出每個元素,並單獨做。
a=[[ 2.22323422 3.34342 ]
[ 24.324 97.56464 ]]
round_to= [[2 1]
[1 3]]
我的預期輸出將是:
a_rounded= [[ 2.2 3. ]
[ 2. 97.6]]
我想這樣做沒有切片出每個元素,並單獨做。
三個選項:
.item
列出理解。itertools.starmap
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
我也想避免for循環,但是謝謝你的迴應。在這種情況下似乎沒有其他選擇。 –
當然可以。剛剛在這個網站上。 –
將24.324舍入到2似乎不合邏輯。 – Psidom
我剛剛從我的袖子里拉出了一個例子,這就是爲什麼我沒有注意到這一點。 –