Home > Enterprise >  create array from lists with specific axis-positions (numpy)
create array from lists with specific axis-positions (numpy)

Time:08-12

this is probably an easy question but I am a python beginner and need some help. I want to transform a list into a 2d array using numpy. There are 2 other lists describing the axis position of the values. f.e.:

list1=[1,2,3] #list with values
list2=[0,1,2] #position x-axis
list3=[2,1,0] #position y-axis

The output should look like this:

[[0 0 3]
 [0 2 0]
 [1 0 0]]

I tried creating an empty array and changing the values but could only do this manually which is not practical. Can someone explain to me how to best go about this? Thanks!

CodePudding user response:

import numpy as np
list1=[1,2,3] #list with values
list2=[0,1,2] #position x-axis
list3=[2,1,0] #position y-axis
output=np.zeros((len(list3),len(list2))) # matrix filled with zeros 3x3
# x and y are reversed in indexing
output[list3,list2]=list1

CodePudding user response:

here is one way :

arr = np.zeros((len(list2),len(list3))) #create array with zeros
arr[list3,list2]=list1

output :

[[0. 0. 3.]
 [0. 2. 0.]
 [1. 0. 0.]]
  • Related