如何对二维数组中的出现次数进行计数和分组?

How to Count and Group Occurences in a 2-D Array?

我正在尝试解析 python 中的二维数据数组,类似于以下内容

[0,0]
[0,2]
[0,4]
[0,3]
[1,4]
[1,3]
[2,6]
[2,3]
[2,4]
[3,8]

首先统计第一列出现的次数,然后以此为基础创建一个数组,并以此为基础进行分组得到,例如:

[0,0]
[0,2]
[0,4]
[0,3]

我正在尝试使用以下方法来做到这一点

import numpy as np

Data = np.zeros(shape = (10,2))
Data = [[0,0],[0,2],[0,4],[0,3],[1,4],[1,3],[2,6],[2,3],[2,4],[3,8]]
print(Data)

for i in range(0,3):
    for j in range(0,10):
        Count = 0
        if i == Data[j,0]:
            Count += 1
        return Count
        DataSet(i) = np.zeros(shape = (Count,2))
        DataSet[i,0] = Data[i,0]
        DataSet[i,1] = Data[i,1]
    print(DataSet[i])

我在获取迭代计数以及填充创建的数组时遇到错误。我该如何改进此代码?

因此,为了重申这个问题,您需要创建一个数组,其中包含第二列中与第一列中的数字相同的所有数字。 在我的回答中,程序创建了一个新数组来保存数字。要检索第一列中所有共享 0 的数字,您将调用:

new_data[0]

这是我创建的代码,希望能够回答您的问题:

Data = [[0,0],[0,2],[0,4],[0,3],[1,4],[1,3],[2,6],[2,3],[2,4],[3,8]]
new_data = []


for i in range(0,4):
    count = 0
    for j in range(0,10):
        if(i == Data[j][0]):
            count += 1
            if(count == 1):
                new_data.append([])
            new_data[i].append(Data[j][1])

print(new_data)

希望对您有所帮助!