gpt4 book ai didi

python - 使用创建的每一行的频率从 numpy 中的矩阵中提取唯一行

转载 作者:太空狗 更新时间:2023-10-30 01:34:35 24 4
gpt4 key购买 nike

后续问题:

How can I use the unique(a, 'rows') from MATLAB in Python?

那里的答案解释了如何获得唯一行。然而,matlab 还会返回创建的每一行的频率。有什么优雅的方法可以用 python 实现吗?

谢谢!

最佳答案

您可以使用花式索引和评估条件来计算每个唯一行的数量,例如:

from numpy import unique, array, all
def myunique(input):
u = array([array(x) for x in set(tuple(x) for x in input)])
return u, array([len(input[all(input==x, axis=1)]) for x in u],dtype=int)

例子:

a = array([list('1234'),
list('1234'),
list('1222'),
list('1222'),
list('1234')],dtype=str)

print myunique(a)
#(array([['1', '2', '2', '2'],
# ['1', '2', '3', '4']],
# dtype='|S1'), array([2, 3]))

关于python - 使用创建的每一行的频率从 numpy 中的矩阵中提取唯一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17137390/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com