4

Example data:

array(
  [[ 1.,  1.],
   [ 2.,  1.],
   [ 0.,  1.],
   [ 0.,  0.],
   [ 0.,  0.]])

with a desired result of

>>> [0.,0.]

ie) The most common pair.

Approaches that don't seem to work:

Using statistics as numpy arrays are unhashable.

Using scipy.stats.mode as this returns the mode over each axis, eg) for our example it gives

mode=array([[ 0.,  1.]])

2 Answers 2

9

You can do this efficiently with numpy using the unique function:

pairs, counts = np.unique(a, axis=0, return_counts=True)
print(pairs[counts.argmax()])

Returns: [ 0. 0.]

Sign up to request clarification or add additional context in comments.

2 Comments

jic anyone needs to know, for .argmax() ~ "In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence are returned."
Note the axis argument is only available in (fairly recent) numpy v.1.13.
2

One way via the standard library is to use collections.Counter.

This gives you both the most common pair and the count. Use [0] index on Counter.most_common() to retrieve the highest count.

import numpy as np
from collections import Counter

A = np.array(
  [[ 1.,  1.],
   [ 2.,  1.],
   [ 0.,  1.],
   [ 0.,  0.],
   [ 0.,  0.]])

c = Counter(map(tuple, A)).most_common()[0]

# ((0.0, 0.0), 2)

The only complication is you need to convert to tuple as Counter only accepts hashable objects.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.