# How do I initialize a NumPy array with a different default for each column?

I am trying to initialize a NumPy matrix of size (x, y) where y is very large.

The first column of the matrix is ββthe identifier (integer) and the rest of the triplets (int8), where each member of the triplet should have a different default value.

i.e. if default values `[2,5,9]`

I would like to initialize the following matrix:

``````0 2 5 9 2 5 9 2 5 9 ...
0 2 5 9 2 5 9 2 5 9 ...
0 2 5 9 2 5 9 2 5 9 ...
0 2 5 9 2 5 9 2 5 9 ...
...
```

```

The fastest way to initialize a matrix is

``````defaults = [2, 5, 9]
mat = numpy.zeros(shape=(x,y),
dtype=['i'] + ['int8'] * (y - 1))
# fill the triplets with default values
for i in range(1, y/3):
j = i * 3
mat[:, j]   = defaults[0]
mat[:, j+1] = defaults[1]
mat[:, j+2] = defaults[2]
```

```

What is the fastest way to initialize such a matrix?

Thank!

+3

source to share

You can use `np.tile`

with changing the array of values, for example:

``````>>> b=np.array([2,5,9])
>>> b=b.reshape(3,1)
>>> np.tile(b,3)
array([[2, 2, 2],
[5, 5, 5],
[9, 9, 9]])
```

```

Then you can use `np.dstack`

to rotate the array and then use `np.hstack`

``````>>> np.hstack((np.zeros((3,1)),np.dstack(new)[0]))
array([[ 0.,  2.,  5.,  9.],
[ 0.,  2.,  5.,  9.],
[ 0.,  2.,  5.,  9.]])
```

```

Or you can repeat the non-zero part again with `tile`

:

``````>>> np.hstack((np.zeros((3,1)),np.tile(np.dstack(new)[0],4)))
array([[ 0.,  2.,  5.,  9.,  2.,  5.,  9.,  2.,  5.,  9.,  2.,  5.,  9.],
[ 0.,  2.,  5.,  9.,  2.,  5.,  9.,  2.,  5.,  9.,  2.,  5.,  9.],
[ 0.,  2.,  5.,  9.,  2.,  5.,  9.,  2.,  5.,  9.,  2.,  5.,  9.]])
```

```

EDIT:

For clarification only, a simple gasket is the following:

``````defaults = [2, 5, 9]
np.hstack((np.zeros((x,1)), np.tile(defaults, (x,y))))
```

```
+1

source

I would do it like this:

``````np.tile([0] + [2, 5, 9] * 4, (3, 1))
```

```

Here I used list addition and list multiplication to create the first row and then used `np.tile`

more than three rows to replicate. `np.tile`

automatically converts the list to an array before iterating vertically three times. You can wrap this in a function that looks something like this if you want,

``````def make_array(triple, n_triple, n_row):
return np.tile([0] + list(triple) * n_triple, (n_row, 1))
```

```

I forced it to `triple`

be a list here, but if you just pass the list to a variable `triple`

when calling this function, you won't need it.

Good luck.

0

source

All Articles