Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create vertical NumPy arrays in Python

I'm using NumPy in Python to work with arrays. This is the way I'm using to create a vertical array:

import numpy as np
a = np.array([[1],[2],[3]])

Is there a simple and more direct way to create vertical arrays?

like image 631
Eghbal Avatar asked Apr 15 '15 18:04

Eghbal


People also ask

How do you vertically stack an array in Python?

vstack() function is used to stack the sequence of input arrays vertically to make a single array. Parameters : tup : [sequence of ndarrays] Tuple containing arrays to be stacked. The arrays must have the same shape along all but the first axis.

How do you flip a NumPy array vertically?

Flip an array vertically (axis=0). Flip an array horizontally (axis=1). flip(m, 0) is equivalent to flipud(m). flip(m, 1) is equivalent to fliplr(m).

How do you concatenate vertically in Python?

Given a String Matrix, perform column-wise concatenation of strings, handling variable lists lengths. Input : [[“Gfg”, “good”], [“is”, “for”]] Output : ['Gfgis', 'goodfor'] Explanation : Column wise concatenated Strings, “Gfg” concatenated with “is”, and so on.


1 Answers

You can use reshape or vstack :

>>> a=np.arange(1,4)
>>> a
array([1, 2, 3])
>>> a.reshape(3,1)
array([[1],
       [2],
       [3]])
>>> np.vstack(a)
array([[1],
       [2],
       [3]])

Also, you can use broadcasting in order to reshape your array:

In [32]: a = np.arange(10)
In [33]: a
Out[33]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In [34]: a[:,None]
Out[34]: 
array([[0],
       [1],
       [2],
       [3],
       [4],
       [5],
       [6],
       [7],
       [8],
       [9]])
like image 178
Mazdak Avatar answered Sep 19 '22 22:09

Mazdak