如何在 python 中对二维数组中的连续数据进行分组

How to group consecutive data in 2d array in python

我有一个二维 NumPy 数组,如下所示:

array([[1, 1],
       [1, 2],
       [2, 1],
       [2, 2],
       [3, 1],
       [5, 1],
       [5, 2]])

我想将它分组并得到如下所示的输出:

         Col1 Col2
group 1: 1-2, 1-2
group 2: 3-3, 1-1
group 3: 5-5, 1-2

我想根据列是否连续对它们进行分组。

因此,对于第 1 列中的唯一值,如果行之间连续,则将第二列中的数据分组。现在,对于第 2 列的唯一分组,如果第 1 列在行之间是连续的,则对第 1 列进行分组。

结果可以看作是网格的角点。在上面的例子中,第1组是一个方格,第2组是一个点,第3组是一条扁线。

我的系统不允许我使用 pandas,所以我不能在该库中使用 group_by,但我可以使用其他标准库。

感谢任何帮助。谢谢

给你...

步骤是:

  • 获取第 xUnique 列唯一值的列表,并保留排序顺序。
  • 构建一个 xRanges 形式的项目列表 [col1_value, [col2_min, col2_max]] 为每个第 1 列的值保留第 2 列的范围。
  • 构建 xGroups 形式的项目列表 [[col1_min, col1_max], [col2_min, col2_max]] 其中 [col1_min, col1_max] 部分是通过合并 [=13= 中连续项目的 col1_value 部分创建的] 如果它们相差 1 并且第 2 列具有相同的 [col2_min, col2_max] 值范围。
  • xGroups 的每一项中的范围转换为字符串并打印所需的行和列标题。
  • 也打包并打印为 numpy.array 以匹配输入的形式。
import numpy as np
data = np.array([
    [1, 1],
    [1, 2],    
    [2, 1],    
    [2, 2],
    [3, 1],
    [5, 1],
    [5, 2]])
xUnique = list({pair[0] for pair in data})
xRanges = list(zip(xUnique, [[0, 0] for _ in range(len(xUnique))]))
rows, cols = data.shape
iRange = -1
for i in range(rows):
    if i == 0 or data[i, 0] > data[i - 1, 0]:
        iRange += 1
        xRanges[iRange][1][0] = data[i, 1]
    xRanges[iRange][1][1] = data[i, 1]
xGroups = []
for i in range(len(xRanges)):
    if i and xRanges[i][0] - xRanges[i - 1][0] == 1 and xRanges[i][1] == xRanges[i - 1][1]:
        xGroups[-1][0][1] = xRanges[i][0]
    else:
        xGroups += [[[xRanges[i][0], xRanges[i][0]], xRanges[i][1]]]

xGroupStrs = [ [f'{a}-{b}' for a, b in row] for row in xGroups]

groupArray = np.array(xGroupStrs)
print(groupArray)

print()
print(f'{"":<10}{"Col1":<8}{"Col2":<8}')
[print(f'{"group " + str(i) + ":":<10}{col1:<8}{col2:<8}') for i, (col1, col2) in enumerate(xGroupStrs)]

输出:

[['1-2' '1-2']
 ['3-3' '1-1']
 ['5-5' '1-2']]

          Col1    Col2
group 0:  1-2     1-2
group 1:  3-3     1-1
group 2:  5-5     1-2