Note

Numpy (49) 본문

Numpy

Numpy (49)

알 수 없는 사용자 2022. 9. 15. 18:53
728x90

How to compute the row wise counts of all possible values in an array?

# Input:
np.random.seed(100)
arr = np.random.randint(1,11,size=(6, 10))
arr

# output

 array([[ 9,  9,  4,  8,  8,  1,  5,  3,  6,  3],
        [ 3,  3,  2,  1,  9,  5,  1, 10,  7,  3],
        [ 5,  2,  6,  4,  5,  5,  4,  8,  2,  2],
        [ 8,  8,  1,  3, 10, 10,  4,  3,  6,  9],
        [ 2,  1,  8,  7,  3,  1,  9,  3,  6,  2],
        [ 9,  2,  6,  5,  3,  9,  4,  6,  1, 10]])
        
# Solution
def counts_of_all_values_rowwise(arr2d):
    # Unique values and its counts row wise
    num_counts_array = [np.unique(row, return_counts=True) for row in arr2d]

    # Counts of all values row wise
    return([[int(b[a==i]) if i in a else 0 for i in np.unique(arr2d)] for a, b in num_counts_array])
 
print(np.arange(1,11))
# output

[ 1  2  3  4  5  6  7  8  9 10]

counts_of_all_values_rowwise(arr)

# output

[[1, 0, 2, 1, 1, 1, 0, 2, 2, 0],
  [2, 1, 3, 0, 1, 0, 1, 0, 1, 1],
  [0, 3, 0, 2, 3, 1, 0, 1, 0, 0],
  [1, 0, 2, 1, 0, 1, 0, 2, 1, 2],
  [2, 2, 2, 0, 0, 1, 1, 1, 1, 0],
  [1, 1, 1, 1, 1, 2, 0, 0, 2, 1]]

'Numpy' 카테고리의 다른 글

Numpy (51)  (0) 2022.09.17
Numpy (50)  (0) 2022.09.16
Numpy (48)  (0) 2022.09.14
Numpy (47)  (0) 2022.09.13
Numpy (46)  (0) 2022.09.12
Comments