gpt4 book ai didi

python - 在 Python 中排除 collections.Counter 中的零

转载 作者:行者123 更新时间:2023-12-05 00:44:57 25 4
gpt4 key购买 nike

有没有办法让collections.Counter不计算/忽略给定值(此处为 0):

from collections import Counter
import numpy as np

idx = np.random.randint(4, size=(100,100))
most_common = np.zeros(100)
num_most_common = np.zeros(100)

for i in range(100):
most_common[i], num_most_common[i] = Counter(idx[i, :]).most_common(1)[0]


所以如果 0是最常见的值,它应该给出第二个最常见的值。另外,在这种情况下有没有办法避免for循环?

最佳答案

对于正数,我们可以使用 vectorized-bincount - bincount2D_vectorized ——

# https://stackoverflow.com/a/46256361/ @Divakar
def bincount2D_vectorized(a):
N = a.max()+1
a_offs = a + np.arange(a.shape[0])[:,None]*N
return np.bincount(a_offs.ravel(), minlength=a.shape[0]*N).reshape(-1,N)

# Get binned counts per row, with each number representing a bin
c = bincount2D_vectorized(idx)

# Skip the first element, as that represents counts for 0s.
# Get most common element and count per row
most_common = c[:,1:].argmax(1)+1
num_most_common = c[:,1:].max(1)
# faster : num_most_common = c[np.arange(len(most_common)),most_common]

对于通用整数,我们可以像这样扩展 -
s = idx.min()
c = bincount2D_vectorized(idx-s)
c[:,-s] = 0
most_common = c.argmax(1)
num_most_common = c[np.arange(len(most_common)),most_common]
most_common += s

关于python - 在 Python 中排除 collections.Counter 中的零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59070129/

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