Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何将一个numpy数组的标签分配给另一个numpy数组并相应地分组?_Python 3.x_Numpy - Fatal编程技术网

Python 3.x 如何将一个numpy数组的标签分配给另一个numpy数组并相应地分组?

Python 3.x 如何将一个numpy数组的标签分配给另一个numpy数组并相应地分组?,python-3.x,numpy,Python 3.x,Numpy,我有以下标签 >>> lab array([2, 2, 2, 2, 2, 3, 3, 0, 0, 0, 0, 1]) 我想将此标签分配给另一个numpy数组,即 >>> arr array([[81, 1, 3, 87], # 2 [ 2, 0, 1, 0], # 2 [13, 6, 0, 0], # 2 [14, 0, 1, 30], # 2 [ 0, 0, 0, 0

我有以下标签

>>> lab
array([2, 2, 2, 2, 2, 3, 3, 0, 0, 0, 0, 1])
我想将此标签分配给另一个numpy数组,即

>>> arr
array([[81,  1,  3, 87],  # 2
       [ 2,  0,  1,  0],  # 2
       [13,  6,  0,  0],  # 2
       [14,  0,  1, 30],  # 2
       [ 0,  0,  0,  0],  # 2
       [ 0,  0,  0,  0],  # 3
       [ 0,  0,  0,  0],  # 3
       [ 0,  0,  0,  0],  # 0
       [ 0,  0,  0,  0],  # 0
       [ 0,  0,  0,  0],  # 0 
       [ 0,  0,  0,  0],  # 0
       [13,  2,  0, 11]]) # 1

并添加第0组、第1组、第2组、第3组的元素?

如果相等值的标签是连续的,如示例所示,则可以使用:

如果它们不连续,则使用对齐数组和标签,使相同值的标签彼此相邻:

>>> i = np.argsort(lab)
>>> lab, arr = lab[i], arr[i, :] # aligns array and labels such that labels
>>> lab                          # are sorted and equal labels are contiguous
array([0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 3, 3])
>>> idx = np.r_[0, 1 + np.where(lab[1:] != lab[:-1])[0]]
>>> np.add.reduceat(arr, idx)
array([[  0,   0,   0,   0],  # 0
       [ 13,   2,   0,  11],  # 1
       [110,   7,   5, 117],  # 2
       [  0,   0,   0,   0]]) # 3
或者使用:


或者使用
np.diff
idx=np.append(0,np.nonzero(np.diff(lab))[0]+1
。但是这个使用np.diff的代码不适用于lab=[1,1,1,0,1,2,3,0,0,0,1,2]@Aparna耶
np.diff
一个只适用于标签连续的情况。如果标签不连续,还有其他方法吗?
>>> i = np.argsort(lab)
>>> lab, arr = lab[i], arr[i, :] # aligns array and labels such that labels
>>> lab                          # are sorted and equal labels are contiguous
array([0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 3, 3])
>>> idx = np.r_[0, 1 + np.where(lab[1:] != lab[:-1])[0]]
>>> np.add.reduceat(arr, idx)
array([[  0,   0,   0,   0],  # 0
       [ 13,   2,   0,  11],  # 1
       [110,   7,   5, 117],  # 2
       [  0,   0,   0,   0]]) # 3
>>> pd.DataFrame(arr).groupby(lab).sum().values
array([[  0,   0,   0,   0],
       [ 13,   2,   0,  11],
       [110,   7,   5, 117],
       [  0,   0,   0,   0]])