NumPy数组和redu

2024-04-28 22:04:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个numpy数组,它有三列形式:

x1 y1 f1


x2 y2 f2


...

xn yn fn

(x,y)对可以重复。我需要另一个数组,这样每个(x,y)对出现一次,对应的第三列是出现在(x,y)旁边的所有f值的总和。在

例如,数组

^{pr2}$

会给予

0 1 9.0

1 1 5.0

1 2 7.0

行的顺序不相关。在Python中实现这一点的最快方法是什么?在

谢谢你!在


Tags: numpy顺序数组形式f2f1fnx1
3条回答

这将是解决问题的一种方法-

import numpy as np

# Input array
A = np.array([[1,2,4.0],
             [1,1,5.0],
             [1,2,3.0],
             [0,1,9.0]])

# Extract xy columns            
xy = A[:,0:2]

# Perform lex sort and get the sorted indices and xy pairs
sorted_idx = np.lexsort(xy.T)
sorted_xy =  xy[sorted_idx,:]

# Differentiation along rows for sorted array
df1 = np.diff(sorted_xy,axis=0)
df2 = np.append([True],np.any(df1!=0,1),0)
# OR df2 = np.append([True],np.logical_or(df1[:,0]!=0,df1[:,1]!=0),0)
# OR df2 = np.append([True],np.dot(df1!=0,[True,True]),0)

# Get unique sorted labels
sorted_labels = df2.cumsum(0)-1

# Get labels
labels = np.zeros_like(sorted_idx)
labels[sorted_idx] = sorted_labels

# Get unique indices
unq_idx  = sorted_idx[df2]

# Get counts and unique rows and setup output array
counts = np.bincount(labels, weights=A[:,2])
unq_rows = xy[unq_idx,:]
out = np.append(unq_rows,counts.ravel()[:,None],1)

输入和输出-

^{pr2}$

当然可以用Python轻松完成:

arr = np.array([[1,2,4.0],
                [1,1,5.0],
                [1,2,3.0],
                [0,1,9.0]])
d={}                
for x, y, z in arr:
    d.setdefault((x,y), 0)
    d[x,y]+=z     

>>> d
{(1.0, 2.0): 7.0, (0.0, 1.0): 9.0, (1.0, 1.0): 5.0}

然后翻译回numpy:

^{pr2}$

多亏了@hpaulj,终于找到了最简单的解决方案。如果d包含3列数据:

ind =d[0:2].astype(int)
x = zeros(shape=(N,N))
add.at(x,list(ind),d[2])

这个解决方案假设前两列中的(x,y)索引是整数并且小于N。这就是我需要的,并且应该在文章中提到。在

编辑:请注意,上面的解决方案生成了一个稀疏矩阵,其和值位于矩阵内的位置(x,y)。在

相关问题 更多 >