如何取消除argmax以外的所有条目?

时间:2018-03-21 16:47:06

标签: python arrays numpy

假设我有一个像def find_unknowns_merge_pattern(vocab, wds): #Both the vocab and wds must be sorted. Return a new #list of words from wds that do not occur in vocab. result = [] xi = 0 yi = 0 while True: if xi >= len(vocab): result.extend(wds[yi:]) return result if yi >= len(wds): return result if vocab[xi] == wds[yi]: # Good, word exists in vocab yi += 1 elif vocab[xi] < wds[yi]: # Move past this vocab word, xi += 1 else: # Got word that is not in vocab result.append(wds[yi]) yi += 1 all_words = get_words_in_book("AliceInWonderland.txt") t0 = time.clock() all_words.sort() book_words = remove_adjacent_dups(all_words) missing_words = find_unknowns_merge_pattern(bigger_vocab, book_words) t1 = time.clock() print("There are {0} unknown words.".format(len(missing_words))) print("That took {0:.4f} seconds.".format(t1-t0)) 这样的矩阵/数组/列表,我想取消除最大值之外的所有条目,因此它将是a=[1,2,3,4,5]

我正在使用a=[0,0,0,0,5]但是有更好(更快)的方式(特别是对于超过1个暗淡的数组......)

2 个答案:

答案 0 :(得分:4)

您可以使用numpy作为就地解决方案。请注意,以下方法将使所有匹配的最大值等于0。

import numpy as np

a = np.array([1,2,3,4,5])

a[np.where(a != a.max())] = 0

# array([0, 0, 0, 0, 5])

对于唯一最大值,请参阅@cᴏʟᴅsᴘᴇᴇᴅ's solution

答案 1 :(得分:3)

您可以创建一个零数组并正确设置正确的索引,而不是屏蔽吗?

1-D(优化)解决方案

(设置)将a转换为1D数组:a = np.array([1,2,3,4,5])

  1. 替换最大

    的一个实例

    b = np.zeros_like(a)
    i = np.argmax(a)
    b[i] = a[i]
    
  2. 替换max

    的所有实例
    b = np.zeros_like(a)
    m = a == a.max()
    b[m] = a[m]
    
  3. N-D解决方案

    np.random.seed(0)
    a = np.random.randn(5, 5)
    

    b = np.zeros_like(a)
    m = a == a.max(1, keepdims=True)
    b[m] = a[m]
    

    b
    array([[0.        , 0.        , 0.        , 2.2408932 , 0.        ],
           [0.        , 0.95008842, 0.        , 0.        , 0.        ],
           [0.        , 1.45427351, 0.        , 0.        , 0.        ],
           [0.        , 1.49407907, 0.        , 0.        , 0.        ],
           [0.        , 0.        , 0.        , 0.        , 2.26975462]])
    

    适用于每行max的所有实例。