Home > Net >  I have a 2D numpy array in python. I want to add the reverse of the elements if not exist
I have a 2D numpy array in python. I want to add the reverse of the elements if not exist

Time:04-14

I have a 2D numpy array. I want to add the reverse of the elements if not exist!

for exapmle, in includes ['113', '722'] and ['722', '113'] and that's good.

array([['113', '1283'],
       ['113', '1108'],
       ['113', '729'],
       ['113', '1059'],
       ['113', '722'],
       ['722', '113'],
       ['113', '937'],
       ['113', '933'],
       ['113', '1050'],
       ['113', '454'],
       ['113', '587']]

CodePudding user response:

Just for loop through the array and using if statement?

import numpy as np

array = np.array([['113', '1283'],
       ['113', '1108'],
       ['113', '729'],
       ['113', '1059'],
       ['113', '722'],
       ['722', '113'],
       ['113', '937'],
       ['113', '933'],
       ['113', '1050'],
       ['113', '454'],
       ['113', '587'])

for item in array:
    item_reversed = item[::-1]
    if item_reversed not in array:
        array.append(item_reversed)

CodePudding user response:

You can do this:

# Switch column order of the original array, where the original array is called n
# and the reversed array is n_rev.
n_rev = n[:, [1, 0]]

# Concatenate reversed and original arrays.
n_fin = np.concatenate((n, n_rev), axis=0)

# Get rid of duplicates.
n_fin = np.unique(n_fin, axis=0)

n_fin holds the results you want. Note that this version does not inclue duplicate rows in n.

EDIT: Here's a version that doesn't remove duplicate rows that are in the original array n:

n[-1] = n[0]
n[-2] = [n[1,1], n[1,0]]

n_rev = n[:, [1, 0]]

# Now find the indices of rows in n_rev that are already in n.
all_idx = []

for i in range(len(n_rev)):
  n_rev_ele = n_rev[i]

  for j in range(len(n)):
    if np.all(np.equal(n_rev_ele, n[j])):
      all_idx.append(i)

# Delete the rows in n_rev that are already in n.
n_rev = np.delete(n_rev, all_idx, axis=0)

# Now concatenate n and n_rev.
n_fin = np.concatenate((n, n_rev), axis=0)
  • Related