Python numpy: reformat list into repeating 2D array

I am new to python and I have a question about numpy.reshape. I currently have 2 lists of values ​​like this:

x = [0,1,2,3]
y = [4,5,6,7]

      

And I want them to be in separate 2D arrays where each element is repeated for the length of the original lists, for example:

xx = [[0,0,0,0]
     [1,1,1,1]
     [2,2,2,2]
     [3,3,3,3]]

yy = [[4,5,6,7]
      [4,5,6,7]
      [4,5,6,7]
      [4,5,6,7]]

      

Is there a way to do this with numpy.reshape, or is there a better method I could use? I would really appreciate a detailed explanation. Thank!

+3


source to share


1 answer


numpy.meshgrid

will do it for you.

NB From your requested output, it looks like you want to index ij

, not the defaultxy

from numpy import meshgrid

x = [0,1,2,3]
y = [4,5,6,7]
xx,yy=meshgrid(x,y,indexing='ij')

print xx
>>> [[0 0 0 0]
     [1 1 1 1]
     [2 2 2 2]
     [3 3 3 3]]

print yy
>>> [[4 5 6 7]
     [4 5 6 7]
     [4 5 6 7]
     [4 5 6 7]]

      



For reference, here's xy

indexing

xx,yy=meshgrid(x,y,indexing='xy')

print xx
>>> [[0 1 2 3]
     [0 1 2 3]
     [0 1 2 3]
     [0 1 2 3]]

print yy
>>> [[4 4 4 4]
     [5 5 5 5]
     [6 6 6 6]
     [7 7 7 7]]

      

+4


source







All Articles