从二维数组创建元组列表

2024-06-26 03:58:06 发布

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

我希望从一个2xn数组创建一个元组列表,其中第一行是ID,第二行是IDs group assignment。我想创建一个ID列表,这些ID被组织到他们的组分配中。在

例如:

array([[ 0.,  1.,  2.,  3.,  4.,  5.,  6.],
       [ 1.,  2.,  1.,  2.,  2.,  1.,  1.])

在上面的示例中,ID 0分配给组1,ID 1分配给组2,依此类推。输出列表如下所示:

^{pr2}$

有没有人有什么创造性的,快速的方法来做到这一点?在

谢谢!在


Tags: 方法idids示例列表group数组array
1条回答
网友
1楼 · 发布于 2024-06-26 03:58:06

标准的(抱歉,不是创造性的,但相当快)裸体方式是一种间接的方式:

import numpy as np

data = np.array([[ 0.,  1.,  2.,  3.,  4.,  5.,  6.],
                 [ 1.,  2.,  1.,  2.,  2.,  1.,  1.]])

index = np.argsort(data[1], kind='mergesort') # mergesort is a bit
                                              # slower than the default
                                              # algorithm but is stable,
                                              # i.e. if there's a tie
                                              # it will preserve order
# use the index to sort both parts of data
sorted = data[:, index]
# the group labels are now in blocks, we can detect the boundaries by
# shifting by one and looking for mismatch
split_points = np.where(sorted[1, 1:] != sorted[1, :-1])[0] + 1

# could convert to int dtype here if desired
result = map(tuple, np.split(sorted[0], split_points))
# That's Python 2. In Python 3 you'd have to explicitly convert to list:
# result = list(result)
print(result)

印刷品:

^{pr2}$

相关问题 更多 >