Group and average NumPy matrix

前端 未结 4 1122
一整个雨季
一整个雨季 2021-02-20 07:46

Say I have an arbitrary numpy matrix that looks like this:

arr = [[  6.0   12.0   1.0]
       [  7.0   9.0   1.0]
       [  8.0   7.0   1.0]
       [  4.0   3.0          


        
4条回答
  •  离开以前
    2021-02-20 08:23

    solution

    from itertools import groupby
    from operator import itemgetter
    
    arr = [[6.0, 12.0, 1.0],
           [7.0, 9.0, 1.0],
           [8.0, 7.0, 1.0],
           [4.0, 3.0, 2.0],
           [6.0, 1.0, 2.0],
           [2.0, 5.0, 2.0],
           [9.0, 4.0, 3.0],
           [2.0, 1.0, 4.0],
           [8.0, 4.0, 4.0],
           [3.0, 5.0, 4.0]]
    
    result = []
    
    for groupByID, rows in groupby(arr, key=itemgetter(2)):
        position1, position2, counter = 0, 0, 0
        for row in rows:
            position1+=row[0]
            position2+=row[1]
            counter+=1
        result.append([position1/counter, position2/counter, groupByID])
    
    print(result)
    

    would output:

    [[7.0, 9.333333333333334, 1.0]]
    [[4.0, 3.0, 2.0]]
    [[9.0, 4.0, 3.0]]
    [[4.333333333333333, 3.3333333333333335, 4.0]]
    

提交回复
热议问题