相关疑难解决方法(0)

根据键转换numpy数组中的每个元素

我试图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.vectorizeDSM提出的方法对于更大的数组要快得多:

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)

python numpy

51
推荐指数
4
解决办法
2万
查看次数

Numpy:对于一个数组中的每个元素,在另一个数组中查找索引

我有两个一维数组,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中,则奖励积分.

python arrays indexing search numpy

39
推荐指数
6
解决办法
3万
查看次数

在numpy中转换一组数字,以便将每个数字转换为一些小于它的其他数字

考虑一组数字:

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以下列方式:每个元素ix,相应的元素jy将其他元素的数量在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)

python numpy python-3.x

8
推荐指数
2
解决办法
210
查看次数

标签 统计

numpy ×3

python ×3

arrays ×1

indexing ×1

python-3.x ×1

search ×1