0

Let's say I have this numpy array:

array([[4, 5, 6, 8, 5, 6],
       [5, 1, 1, 9, 0, 5],
       [7, 0, 5, 8, 0, 5],
       [9, 2, 3, 8, 2, 3],
       [1, 2, 2, 9, 2, 8]])

And going row by row, I would like to see, by column, the cumulative count of the number that appears. So for this array, the result would be:

array([[0, 0, 0, 0, 0, 0],  # (*0) 
       [0, 0, 0, 0, 0, 0],  # (*1) 
       [0, 0, 0, 1, 1, 1],  # (*2)
       [0, 0, 0, 2, 0, 0],  # (*3)
       [0, 1, 0, 1, 1, 0]]  # (*4)
  • (*0): first time each value appears
  • (*1): all values are different from the previous one (in the column)
  • (*2): For the last 3 columns, a 1 appears because there is already 1 value repetition.
  • (*3): For the 4th column, a 2 appears because it's the 3rd time that a 8 appears.
  • (*4): In the 4th column, a 1 appears because it's the 2nd time that a 9 appears in that column. Similarly, for the second and second to last column.

Any idea how to perform this?

Thanks!

1 Answer 1

1

Maybe there is a faster way using numpy ufuncs, however here is a solution using standard python:

from collections import defaultdict
import numpy as np

a = np.array([[4, 5, 6, 8, 5, 6],
              [5, 1, 1, 9, 0, 5],
              [7, 0, 5, 8, 0, 5],
              [9, 2, 3, 8, 2, 3],
              [1, 2, 2, 9, 2, 8]])

# define function
def get_count(array):
    count = []
    for row in array.T:
        occurences = defaultdict(int)
        rowcount = []
        for n in row:
            occurences[n] += 1
            rowcount.append(occurences[n] - 1)
        count.append(rowcount)
    return np.array(count).T

Output:

>>> get_count(a)
array([[0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0],
       [0, 0, 0, 1, 1, 1],
       [0, 0, 0, 2, 0, 0],
       [0, 1, 0, 1, 1, 0]])
Sign up to request clarification or add additional context in comments.

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.