Compare 1 Column Of 2d Array And Remove Duplicates Python
Say I have a 2D array like: array = [['abc',2,3,], ['abc',2,3], ['bb',5,5], ['bb',4,6], ['sa',3,5], ['tt',2,1]] I want to remove any rows
Solution 1:
Similar to other answers, but using a dictionary instead of importing counter:
counts= {}
for elem in array:# add 1 to counts for this string, creating new element at this key# with initial value of 0 if neededcounts[elem[0]]=counts.get(elem[0],0)+1new_array= []
for elem in array:# check that there's only 1 instance of this element.ifcounts[elem[0]]==1:new_array.append(elem)
Solution 2:
One option you can try is create a counter for the first column of your array before hand and then filter the list based on the count value, i.e, keep the element only if the first element appears only once:
from collections import Counter
count = Counter(a[0] for a in array)
[a for a in array if count[a[0]] == 1]
# [['sa', 3, 5], ['tt', 2, 1]]
Solution 3:
You can use a dictionary and count the occurrences of each key.
You can also use Counter
from the library collections that actually does this.
Do as follows :
from collection importCounterremoved= []
for k, val1, val2 in array:
ifCounter([k for k, _, _ in array])[k]==1:
removed.append([k, val1, val2])
Post a Comment for "Compare 1 Column Of 2d Array And Remove Duplicates Python"