Home > OS >  How to remove duplicates from a 2 dimensional numpy array
How to remove duplicates from a 2 dimensional numpy array

Time:10-17

I have a numpy array that contains multipal numpy arrays, each one of them contains the cartesian coordinates of two cornernodes of a line like:

array(array([0,10,10], [10,20,20]),
      array([0,10,20], [10,10,20]),
      array([10,10,10], [10,20,20]),
      array([10,20,20], [0,10,10]))

how can i remove the duplicated node pairs like the first and the last one in this example? outlook should look like:

array(array([0,10,10], [10,20,20]),
      array([0,10,20], [10,10,20]),
      array([10,10,10], [10,20,20]))

These nodes are the corner nodes of an FE-Mesh and die node pairs represent all edges in the mesh. I got some edges in both direction (node1, node2) and (node1,node1) but i only need the edge one time so i have to remove the second one.

CodePudding user response:

Following is a very basic O(n^2) iteration logic to solve this:

arr = [
  [[0,10,20], [10,10,20]], 
  [[0,10,10], [10,20,20]], 
  [[10,20,20], [0,10,10]],
  [[10,10,10], [10,20,20]], 
]

for i in range(len(arr)-1, 0, -1):
  duplicate_found = False
  for j in range(i-1, -1, -1):
    if (arr[i][0] == arr[j][0] and arr[i][1] == arr[j][1]) or (arr[i][0] == arr[j][1] and arr[i][1] == arr[j][0]):
      duplicate_found = True
      break
  if duplicate_found:
    del arr[i]

print(arr)
>> [[[0, 10, 20], [10, 10, 20]],
>>  [[0, 10, 10], [10, 20, 20]],
>>  [[10, 10, 10], [10, 20, 20]]]

  • Related