代码之家  ›  专栏  ›  技术社区  ›  Sergej Fomin

Python在数组中找到最常见的值

  •  0
  • Sergej Fomin  · 技术社区  · 7 年前
    import numpy as np 
    x = ([1,2,3,3])
    y = ([1,2,3])
    z = ([6,6,1,2,9,9])
    

    (仅正值) 在每个数组中,我需要返回最常用的值,或者,如果值达到相同的次数,则返回最小值。 这是家庭作业,除了钱我什么都用不了。

    输出:

    f(x) = 3,
    f(y) = 1,
    f(z) = 6
    
    5 回复  |  直到 7 年前
        1
  •  1
  •   Inder Manali    7 年前

    对于Numpy独家解决方案,类似这样的解决方案将起作用:

    occurances = np.bincount(x)
    print (np.argmax(occurances))
    

    如果列表中有负数,上述方法将不起作用。因此,为了解释这种情况,请使用:

    not_required, counts = np.unique(x, return_counts=True)
    x=np.array(x)
    if (x >= 0).all():
        print(not_required[np.argmax(counts)])
    else:    
        print(not_required[np.argmax(counts)])
    
        2
  •  1
  •   blue_note    7 年前
        3
  •  0
  •   madmatrix    7 年前

    没有纽比

    n_dict = {}
    for k in x:
        try:
            n_dict[k] += 1
        except KeyError:
            n_dict[k] = 1
    
    rev_n_dict = {}
    for k in n_dict:
        if n_dict[k] not in rev_n_dict:
            rev_n_dict[n_dict[k]] = [k]
        else:
            rev_n_dict[n_dict[k]].append(k)
    
    local_max = 0
    for k in rev_n_dict:
        if k > local_max:
            local_max = k
    
    if len(rev_n_dict[local_max]) > 0:      
        print (min(rev_n_dict[local_max]))
    else:
        print (rev_n_dict[local_max])
    
        4
  •  0
  •   Learning is a mess    7 年前

    要添加到以前的结果,可以使用 collections.Counter 对象:

     my_array =  [3,24,543,3,1,6,7,8,....,223213,13213]
     from collections import Counter
     my_counter = Counter( my_array)
     most_common_value = my_counter.most_common(1)[0][0]
    
        5
  •  0
  •   Inder Manali    7 年前

    它很简单,但肯定不漂亮我使用了变量名,这些变量名和注释一起都是不言而喻的。如果有疑问,请随时询问。

    import numpy as np
    x=([6,6,1,2,9,9])
    
    def tester(x): 
        not_required, counts = np.unique(x, return_counts=True)
        x=np.array(x)
        if (x >= 0).all():
            highest_occurance=[not_required[np.argmax(counts)]]
            number_of_counts=np.max(counts)
    
        else:    
            highest_occurance=not_required[np.argmax(counts)]
            number_of_counts=np.max(counts)
    
        return highest_occurance,number_of_counts
    
    most_abundant,first_test_counts=(tester(x))
    
    new_x=[vals for vals in x if vals not in most_abundant]
    
    second_most_abundant,second_test_counts=(tester(new_x))
    
    if second_test_counts==first_test_counts:
        print("Atleast two elements have the same number of counts",most_abundant," and", second_most_abundant, "have %s"%first_test_counts,"occurances")
    else:
        print("%s occurrs for the max of %s times"%(most_abundant,first_test_counts))
    

    我们还可以循环它来检查是否有两个以上的元素具有相同的事件,而不是使用if-else来处理只查看两个元素的特定情况