我有一个形状为(1000,)
的一维numpy数组X。我想在随机(均匀)位置注入10个随机(正常)值,从而获得形状(1010,)
的numpy数组。如何在numpy中有效地做到这一点?
答案 0 :(得分:3)
您可以将np.insert
与np.random.choice
一起使用:
n = 10
np.insert(a, np.random.choice(len(a), size=n), np.random.normal(size=n))
答案 1 :(得分:1)
这里是基于遮罩的-
def addrand(a, N):
n = len(a)
m = np.concatenate((np.ones(n, dtype=bool), np.zeros(N, dtype=bool)))
np.random.shuffle(m)
out = np.empty(len(a)+N, dtype=a.dtype)
out[m] = a
out[~m] = np.random.uniform(N)
return out
样品运行-
In [22]: a = 10+np.random.rand(20)
In [23]: a
Out[23]:
array([10.65458302, 10.18034826, 10.08652451, 10.03342622, 10.63930492,
10.48439184, 10.2859206 , 10.91419282, 10.56905636, 10.01595702,
10.21063965, 10.23080433, 10.90546147, 10.02823502, 10.67987108,
10.00583747, 10.24664158, 10.78030108, 10.33638157, 10.32471524])
In [24]: addrand(a, N=3) # adding 3 rand numbers
Out[24]:
array([10.65458302, 10.18034826, 10.08652451, 10.03342622, 0.79989563,
10.63930492, 10.48439184, 10.2859206 , 10.91419282, 10.56905636,
10.01595702, 0.23873077, 10.21063965, 10.23080433, 10.90546147,
10.02823502, 0.66857723, 10.67987108, 10.00583747, 10.24664158,
10.78030108, 10.33638157, 10.32471524])
时间:
In [71]: a = np.random.rand(1000)
In [72]: %timeit addrand(a, N=10)
37.3 µs ± 273 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
# @a_guest's soln
In [73]: %timeit np.insert(a, np.random.choice(len(a), size=10), np.random.normal(size=10))
63.3 µs ± 2.18 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
注意:如果使用更大的数组,似乎np.insert
会做得更好。
答案 2 :(得分:0)
不确定这是否是最有效的方法,但至少可以奏效。
A = np.arange(1000)
for i in np.random.randint(low = 0, high = 1000, size = 10):
A = np.concatenate((A[:i], [np.random.normal(),], A[i:]))
编辑,检查性能:
def insert_random(A):
for i in np.random.randint(low = 0, high = len(A), size = 10):
A = np.concatenate((A[:i], [np.random.normal(),], A[i:]))
return A
A = np.arange(1000)
%timeit test(A)
83.2 µs ± 2.47 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
所以绝对不是最有效的。 np.insert
似乎是要走的路。
答案 3 :(得分:0)
您可以使用import numpy as np
a = np.arange(1000)
a = np.insert(a, np.random.randint(low = 1, high = 999, size=10), np.random.normal(loc=0.0, scale=1.0, size=10))
。
insert
请记住,using Distributed
addprocs(2)
@everywhere using DistributedArrays
@everywhere using LinearAlgebra
n=10
Z=zeros(n,n)
#Z[1,:].=200
#Z[:,end].=200
Z=distribute(Z; dist=(2,1))
K=ones(n,1)
#K[1,:].=200
#K[end,:].=200
K=distribute(K; dist=(2,1))
#(i+1) % 2)+1,j
@sync @distributed for x in 1:nworkers()
localpart(Z)[1,:].=200
@sync @distributed for i in 2:length(localindices(Z)[1])
for j in 1:length(localindices(Z)[2])
localpart(Z)[i,j]=10*log(myid())+localpart(K)[i]
end
end
end
end
Z
不会自动更改原始数组,但是会返回修改后的副本。