我试图numpy.array
根据给定的密钥翻译a的每个元素:
例如:
a = np.array([[1,2,3],
[3,2,4]])
my_dict = {1:23, 2:34, 3:36, 4:45}
Run Code Online (Sandbox Code Playgroud)
我想得到:
array([[ 23., 34., 36.],
[ 36., 34., 45.]])
Run Code Online (Sandbox Code Playgroud)
我可以看到如何使用循环:
def loop_translate(a, my_dict):
new_a = np.empty(a.shape)
for i,row in enumerate(a):
new_a[i,:] = map(my_dict.get, row)
return new_a
Run Code Online (Sandbox Code Playgroud)
是否有更高效和/或纯粹的numpy方式?
编辑:
我计时了,np.vectorize
DSM提出的方法对于更大的数组要快得多:
In [13]: def loop_translate(a, my_dict):
....: new_a = np.empty(a.shape)
....: for i,row in enumerate(a):
....: new_a[i,:] = map(my_dict.get, row)
....: return new_a
....:
In [14]: def vec_translate(a, my_dict):
....: return np.vectorize(my_dict.__getitem__)(a)
....:
In [15]: a …
Run Code Online (Sandbox Code Playgroud) 我有两个一维数组,x和y,一个比另一个小.我试图在x中找到y的每个元素的索引.
我发现了两种天真的方法,第一种是缓慢的,第二种是内存密集型.
indices= []
for iy in y:
indices += np.where(x==iy)[0][0]
Run Code Online (Sandbox Code Playgroud)
xe = np.outer([1,]*len(x), y)
ye = np.outer(x, [1,]*len(y))
junk, indices = np.where(np.equal(xe, ye))
Run Code Online (Sandbox Code Playgroud)
有更快的方式或更少的内存密集型方法吗?理想情况下,搜索将利用这样一个事实,即我们在列表中搜索的不是一件事,而是很多事情,因此稍微更适合并行化.如果您不假设y的每个元素实际上都在x中,则奖励积分.
考虑一组数字:
In [8]: import numpy as np
In [9]: x = np.array([np.random.random() for i in range(10)])
In [10]: x
Out[10]:
array([ 0.62594394, 0.03255799, 0.7768568 , 0.03050498, 0.01951657,
0.04767246, 0.68038553, 0.60036203, 0.3617409 , 0.80294355])
Run Code Online (Sandbox Code Playgroud)
现在,我想这组变换成另一组y
以下列方式:每个元素i
中x
,相应的元素j
在y
将其他元素的数量在x
这不到i
.例如,上面给出的内容x
如下:
In [25]: y
Out[25]: array([ 6., 2., 8., 1., 0., 3., 7., 5., 4., 9.])
Run Code Online (Sandbox Code Playgroud)
现在,我可以使用简单的python循环来做到这一点:
In [16]: for i in range(len(x)):
...: tot = 0
...: for j in …
Run Code Online (Sandbox Code Playgroud)