mat = [ [1,3,5,7], [1,2,5,7], [8,2,3,4] ]
我必须设计一个函数,该函数可以考虑参考行来计算具有相同值(每列)的行数。
每行的结果数组将是
row0 = [2,1,2,2]
row1 = [2,2,2,2]
row3 = [1,2,1,1]
矩阵垫的每一行都是用户,每一列都是用户在定义的时间单位中位置的标签。因此,我必须在每个定义的时间(即列)中统计有多少用户共享同一职位。
我尝试使用numpy count_nonzero函数,但它需要一个条件,即我无法在所有参考行上进行扩展
最佳答案
这是使用`argsort的numpy
解决方案。这可以处理非整数条目:
import numpy as np
def count_per_col(a):
o = np.argsort(a, 0)
ao = np.take_along_axis(a, o, 0)
padded = np.ones((ao.shape[1], ao.shape[0]+1), int)
padded[:, 1:-1] = np.diff(ao, axis=0).T
i, j = np.where(padded)
j = np.maximum(np.diff(j), 0)
J = j.repeat(j)
out = np.empty(a.shape, int)
np.put_along_axis(out, o, J.reshape(out.shape[::-1]).T, 0)
return out
mat = np.array([[1,3,5,7], [1,2,5,7], [8,2,3,4]])
count_per_col(mat)
# array([[2, 1, 2, 2],
# [2, 2, 2, 2],
# [1, 2, 1, 1]])
多快?
from timeit import timeit
large = np.random.randint(0, 100, (100, 10000))
large = np.random.random(100)[large]
timeit(lambda: count_per_col(large), number=10)/10
# 0.1332556433044374
关于python-3.x - 根据python矩阵中特定行中的值对列值进行计数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55118291/