2

I have an array where each element is the mean of a set of random numbers. I want to be able to remove duplicate values in this array. How would I go about doing this?

So far I have tried:

for i in range(len(array)):
 
 for j in array:
 if array[i] == j:

and then some operation to remove the element from the array. However, this will just remove every instance of every duplicated element.

asked Mar 22, 2022 at 10:31

5 Answers 5

4

You could simply use np.unique():

unique_values = np.unique(array)
answered Mar 22, 2022 at 10:35
3

If you don't care about the order of the elements then use the following

deduplicated = list(set(array))
answered Mar 22, 2022 at 10:37
2

You can try to create the array of a set:

deduplicated_array = list(set(array))
answered Mar 22, 2022 at 10:34
2

This way was worked for me (Ways to remove duplicates from list):

res = []
[res.append(x) for x in test_list if x not in res]
# printing list after removal 
print ("The list after removing duplicates : " + str(res))
answered May 11, 2022 at 4:29
0

You may want to look into using a python set :)

Example with code:

# set cannot have duplicates
# Output: {1, 2, 3, 4}
my_set = {1, 2, 3, 4, 3, 2}
print(my_set)
# we can make set from a list: what you want
# Output: {1, 2, 3}
my_set = set([1, 2, 3, 2])
print(my_set)

Then you can use remove or discard (if you don't want errors upon removing non-existing items):

my_set = {1, 3, 4, 5, 6}
print(my_set)
# discard an element
# Output: {1, 3, 5, 6}
my_set.discard(4)
print(my_set)
# remove an element
# Output: {1, 3, 5}
my_set.remove(6)
print(my_set)
# discard an element
# not present in my_set
# Output: {1, 3, 5}
my_set.discard(2)
print(my_set)
# remove an element
# not present in my_set
# you will get an error.
# Output: KeyError
my_set.remove(2)

If you prefer to work with a list, then you can then convert back to a list with the list function:

my_list = list(my_set)

Docs: https://python-reference.readthedocs.io/en/latest/docs/sets/

answered Mar 22, 2022 at 10:34

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.