Is there a multi-dimensional version of arange/linspace in numpy?

前端 未结 9 1456
有刺的猬
有刺的猬 2020-12-02 08:31

I would like a list of 2d NumPy arrays (x,y) , where each x is in {-5, -4.5, -4, -3.5, ..., 3.5, 4, 4.5, 5} and the same for y.

I could do

x = np.ar         


        
相关标签:
9条回答
  • 2020-12-02 09:18

    If you just want to iterate through pairs (and not do calculations on the whole set of points at once), you may be best served by itertools.product to iterate through all possible pairs:

    import itertools
    
    for (xi, yi) in itertools.product(x, y):
        print(xi, yi)
    

    This avoids generating large matrices via meshgrid.

    0 讨论(0)
  • 2020-12-02 09:21

    This is just what you are looking for:

    matr = np.linspace((1,2),(10,20),10)
    

    This means:

    For the first column; from 1 of (1,2) to 10 of (10,20), put the increasing 10 numbers.

    For the second column; from 2 of (1,2) to 20 of (10,20), put the incresing 10 numbers.

    And the result will be:

    [[ 1.  2.]
     [ 2.  4.]
     [ 3.  6.]
     [ 4.  8.]
     [ 5. 10.]
     [ 6. 12.]
     [ 7. 14.]
     [ 8. 16.]
     [ 9. 18.]
     [10. 20.]]
    

    You may also keep only one column's values increasing, for example, if you say that:

    matr = np.linspace((1,2),(1,20),10)
    

    The first column will be from 1 of (1,2) to 1 of (1,20) for 10 times which means that it will stay as 1 and the result will be:

    [[ 1.  2.]
     [ 1.  4.]
     [ 1.  6.]
     [ 1.  8.]
     [ 1. 10.]
     [ 1. 12.]
     [ 1. 14.]
     [ 1. 16.]
     [ 1. 18.]
     [ 1. 20.]]
    
    0 讨论(0)
  • 2020-12-02 09:21

    We can use arrange function as:

    z1 = np.array([np.array(np.arange(1,5)),np.array(np.arange(1,5))])
    print(z1)
    o/p=> [[1 2 3 4]
           [1 2 3 4]]
    
    0 讨论(0)
提交回复
热议问题