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!
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]]]
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!
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]]]