Bob5421
Bob5421

Reputation: 9063

How to add dimension to a python numpy array

Let's suppose i have this array:

import numpy as np
x = np.arange(4)

array([0, 1, 2, 3])

I want to write a very basic formula which will generate from x this array:

array([[0, 1, 2, 3],
       [1, 2, 3, 4],
       [2, 3, 4, 5],
       [3, 4, 5, 6]])

What is the shortest way to do that with python and numpy ?

Thanks

Upvotes: 1

Views: 158

Answers (2)

Allen Qin
Allen Qin

Reputation: 19947

The easiest way I can think of is to use numpy broadcasting.

x[:,None]+x
Out[87]: 
array([[0, 1, 2, 3],
       [1, 2, 3, 4],
       [2, 3, 4, 5],
       [3, 4, 5, 6]])

Upvotes: 1

Tom de Geus
Tom de Geus

Reputation: 5955

This should do what you want (note that I have introduced a different number of rows (5) than of columns (4) to make a clear distinction):

import numpy as np

A = np.tile(np.arange(4).reshape(1,4),(5,1))+np.tile(np.arange(5).reshape(5,1),(1,4))

print(A)

A break-down of steps:

  1. np.tile(np.arange(4).reshape(1,4),(5,1)) creates a (5,4) matrix with entries 0,1,2,3 in each row:

    [[0 1 2 3]
     [0 1 2 3]
     [0 1 2 3]
     [0 1 2 3]
     [0 1 2 3]]
    
  2. np.tile(np.arange(5).reshape(5,1),(1,4)) creates a (5,4) matrix with 0,1,2,3,4 in each column:

    [[0 0 0 0]
     [1 1 1 1]
     [2 2 2 2]
     [3 3 3 3]
     [4 4 4 4]]
    
  3. The sum of the two results in what you want:

    [[0 1 2 3]
     [1 2 3 4]
     [2 3 4 5]
     [3 4 5 6]
     [4 5 6 7]]
    

Upvotes: 0

Related Questions