Hello all,
I would be grateful for your advice regarding something I tried to do using unique() but it didn't work.
I have a two dimensional numpy array that looks like that (but much larger):
>>> pop_A1
array([[10, 2, 10],
[10, 9, 10],
[10, 9, 10],
[10, 9, 10],
[10, 9, 10],
[22, 9, 10],
[10, 9, 10],
[10, 9, 10],
[10, 9, 10],
[10, 9, 10]])
From that I need to create a unique list (or array), specifying unique vectors and how many of each of them are there. So for example, I have here 3 unique vectors which are [10, 2, 10], [10, 9, 10] and [22, 9, 10]. The first vector appears one time, the second appears 8 times, and the third appear one time, so I would like my output be something like:
[10, 2, 10] 1
[10, 9, 10] 8
[22, 9, 10] 1
When I use unique() it seems to "flatten" the two dimensional array, and I only get:array([ 2, 9, 10, 22]).
Many thanks for any suggestion!

Recommended Answers

All 2 Replies

You can use a dictionary as a counter, but you first have to convert the key to a tuple.

arr=[[10, 2, 10],
[10, 9, 10],
[10, 9, 10],
[10, 9, 10],
[10, 9, 10],
[22, 9, 10],
[10, 9, 10],
[10, 9, 10],
[22, 9, 10],
[10, 9, 10]]

unique_dict = {}
for x in arr:
   ## convert to a tuple so it is hashable
   y = tuple(x)
   if y not in unique_dict:
       unique_dict[y] = 0
   unique_dict[y] += 1

print unique_dict

Thanks a lot woooee, it works great!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.