Home > other >  Preserving a two dimensional array after applying a function in Python
Preserving a two dimensional array after applying a function in Python

Time:06-22

I am trying to apply a function to a two dimensional array, however I want the output to be a two dimensional array as well, I want it to preserve the same stucture after each element is transformed by the function. I have created the following simple case, however my output is:

[101, 103, 104, 105, 105, 104, 198, 199, 948, 132, 106, 106]

instead of a two dimensional array of the same shape as the original. Here follows the code so that you can replicate:

Vamos = [
  [2, 4, 5, 6],
  [6, 5, 99,100],
  [849, 33, 7, 7]
]

Vamos1=[]

for j in range(len(Vamos)):
    for i in range(len(Vamos[1])):
        Vamos2=(Vamos[j][i]) 99
        
        Vamos1.append(Vamos2)

Vamos1

Thanks in advance.

CodePudding user response:

Python isn't magically going to split your list into 2D if you throw all the items into it in a double loop.

Vamos = [
  [2, 4, 5, 6],
  [6, 5, 99,100],
  [849, 33, 7, 7]
]

Vamos1=[]

for j in range(len(Vamos)):
    row = []
    for i in range(len(Vamos[1])):
        Vamos2=(Vamos[j][i]) 99
        
        row.append(Vamos2)
    Vamos1.append(row)
    
print(Vamos1)

CodePudding user response:

Just convert the list to a numpy array and add 99:

import numpy as np
Vamos1 = np.array(Vamos) 99

CodePudding user response:

you can just use Numpy library to do this:

import numpy as np

vamos = np.array([[2, 4, 5, 6],
                  [6, 5, 99,100],
                  [849, 33, 7, 7]]
                  )
vamos_2 = vamos   99

You can perform all list operation on numpy arrays. But if you want absolutely to have list, you can just do:

list(vamos_2)
  • Related