Get elements for the same values in numpy

Question:

There is a numpy matrix:

bins =array([[2076., -861.84471079],
       [2076., -858.23866597],
       [2076., -861.84471079],
       ...,
       [9757., 1847.33889178],
       [9757., 1830.39082856],
       [9757., -932.14347751]])

I want to collect all the elements along the 1 axis for each unique value along the 0 axis:

bins = array([[2076., [-861.84471079, -858.2386, -861.84471]],
       [9757., [1847.33889178, 1830.3908, -932.14]]])

etc

I did as follows:

bins = points_OYZ[points_OYZ[:, 0].argsort()]

vals, idx_start, count = np.unique(bins[:, 0], return_counts=True, return_index=True)

binarize_matrix = np.split(bins, idx_start[1:])

q = []
for i in binarize_matrix:
    min_index = np.argmin(i[:, 1])
    q.append(i[min_index])

I would like it to be simpler, but I don’t know how, please tell me!

Asked By: Opacho And

||

Answers:

Is this what you would like to do

import numpy as np

bins = np.array([[2076., -861.84471079],
             [2076., -858.23866597],
             [2076., -861.84471079],
             [9757., 1847.33889178],
             [9757., 1830.39082856],
             [9757., -932.14347751],
             [9760., -159.14347751]])

vals, idx_start, count = np.unique(bins[:, 0], return_counts=True, return_index=True)

output = [[vals[i], bins[idx_start[i]:idx_start[i]+count[i]][:, 1].tolist()] for i in range(len(vals))]
print(output)

output:

[[2076.0, [-861.84471079, -858.23866597, -861.84471079]], 
 [9757.0, [1847.33889178, 1830.39082856, -932.14347751]], 
 [9760.0, [-159.14347751]]]
Answered By: Ajeet Verma
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.