我有一个Numpy数组和一个索引列表,其值我想增加一个.此列表可能包含重复索引,我希望增量与每个索引的重复次数一致.没有重复,命令很简单:
a=np.zeros(6).astype('int')
b=[3,2,5]
a[b]+=1
Run Code Online (Sandbox Code Playgroud)
有了重复,我想出了以下方法.
b=[3,2,5,2] # indices to increment by one each replicate
bbins=np.bincount(b)
b.sort() # sort b because bincount is sorted
incr=bbins[np.nonzero(bbins)] # create increment array
bu=np.unique(b) # sorted, unique indices (len(bu)=len(incr))
a[bu]+=incr
Run Code Online (Sandbox Code Playgroud)
这是最好的方法吗?假设np.bincount和np.unique操作会产生相同的排序顺序是否存在风险?我错过了一些简单的Numpy操作来解决这个问题吗?
我试图计算每行显示的数字np.array,例如:
import numpy as np
my_array = np.array([[1, 2, 0, 1, 1, 1],
[1, 2, 0, 1, 1, 1], # duplicate of row 0
[9, 7, 5, 3, 2, 1],
[1, 1, 1, 0, 0, 0],
[1, 2, 0, 1, 1, 1], # duplicate of row 0
[1, 1, 1, 1, 1, 0]])
Run Code Online (Sandbox Code Playgroud)
行[1, 2, 0, 1, 1, 1]显示3次.
一个简单的天真解决方案将涉及将我的所有行转换为元组,并应用collections.Counter,如下所示:
from collections import Counter
def row_counter(my_array):
list_of_tups = [tuple(ele) for ele in my_array]
return …Run Code Online (Sandbox Code Playgroud)