[Python] How to Mark Repeated Entries as True Starting from the Second Occurrence Using NumPy?

Discussão em 'Python' iniciado por Stack, Novembro 20, 2024.

  1. Stack

    Stack Membro Participativo

    Problem


    I have a NumPy array and need to identify repeated elements, marking the second occurrence and beyond as True, while keeping the first occurrence as False.

    For example, given the following array:

    np.random.seed(100)
    a = np.random.randint(0, 5, 10)
    # Output: [0 0 3 0 2 4 2 2 2 2]


    I want to get the following output:

    [False True False True False False True True True True]


    How can I achieve this using NumPy functions only, without using any loops or extra libraries?

    What did you try and what were you expecting?


    I was able to get it working with a loop, but I wanted to solve it using only NumPy functions. I tried implementing np.cumsum with masks, but I couldn’t make much progress.

    Here's the solution I came up with using one loop:

    np.random.seed(100)
    a = np.random.randint(0, 5, 10)
    print(a)
    uniques, first_indices = np.unique(a, return_index=True)
    all_occurrences = np.zeros_like(a, dtype=bool)
    for i in range(len(a)):
    all_occurrences = np.any(a[:i] == a)

    all_occurrences[first_indices] = False
    print(all_occurrences)

    Continue reading...

Compartilhe esta Página