Append a 1d array to a 2d array in Numpy Python - python

I have a numpy 2D array [[1,2,3]].
I need to append a numpy 1D array,( say [4,5,6]) to it, so that it becomes [[1,2,3], [4,5,6]]
This is easily possible using lists, where you just call append on the 2D list.
But how do you do it in Numpy arrays?
np.concatenate and np.append dont work. they convert the array to 1D for some reason.
Thanks!

You want vstack:
In [45]: a = np.array([[1,2,3]])
In [46]: l = [4,5,6]
In [47]: np.vstack([a,l])
Out[47]:
array([[1, 2, 3],
[4, 5, 6]])
You can stack multiple rows on the condition that The arrays must have the same shape along all but the first axis.
In [53]: np.vstack([a,[[4,5,6], [7,8,9]]])
Out[53]:
array([[1, 2, 3],
[4, 5, 6],
[4, 5, 6],
[7, 8, 9]])

Try this:
np.concatenate(([a],[b]),axis=0)
when
a = np.array([1,2,3])
b = np.array([4,5,6])
then result should be:
array([[1, 2, 3],
[4, 5, 6]])

Related

how do you create subarray from 1st column of a 2d array in numpy

Using numpy, how is it possible to take the array
np.array([[1,2,3],[4,5,6],[7,8,9]])
and get out the arrays
[1,4,7] and [[2,3],[5,6],[8,9]]
You can use indexing as such :
In [9]: a = np.array([[1,2,3],[4,5,6],[7,8,9]])
In [10]: a[:,0]
Out[10]: array([1, 4, 7])
In [11]: a[:,1:]
Out[11]:
array([[2, 3],
[5, 6],
[8, 9]])

How to create a 2d numpy ndarray using two list comprehensions

I tried to create a 2D numpy ndarray using the following code:
temp = np.array([[np.mean(w2v[word]) for word in docs if word in w2v] for docs in X[:5]])
temp has a shape of (5,) instead of expected (5,x).
Also temps's data structure is like: array([list([.....],...)])
It seems that the inner list is not converted to ndarray.
Your missing np.array in there, it should be:
temp = np.array([np.array([np.mean(w2v[word]) for word in docs if word in w2v] for docs in X[:5])])
Running example:
bob
Out[70]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
tmp = np.array([np.array([x for x in Y]) for Y in bob])
tmp
Out[72]:
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])

Numpy Search & Slice 3D Array

I'm very new to Python & Numpy and am trying to accomplish the following:
Given, 3D Array:
arr_3d = [[[1,2,3],[4,5,6],[0,0,0],[0,0,0]],
[[3,2,1],[0,0,0],[0,0,0],[0,0,0]]
[[1,2,3],[4,5,6],[7,8,9],[0,0,0]]]
arr_3d = np.array(arr_3d)
Get the indices where [0,0,0] appears in the given 3D array.
Slice the given 3D array from where [0,0,0] appears first.
In other words, I'm trying to remove the padding (In this case: [0,0,0]) from the given 3D array.
Here is what I have tried,
arr_zero = np.zeros(3)
for index in range(0, len(arr_3d)):
rows, cols = np.where(arr_3d[index] == arr_zero)
arr_3d[index] = np.array(arr_3d[0][:rows[0]])
But doing this, I keep getting the following error:
Could not broadcast input array from shape ... into shape ...
I'm expecting something like this:
[[[1,2,3],[4,5,6]],
[[3,2,1]]
[[1,2,3],[4,5,6],[7,8,9]]]
Any help would be appreciated.
Get the first occurance of those indices with all() reduction alongwith argmax() and then slice each 2D slice off the 3D array -
In [106]: idx = (arr_3d == [0,0,0]).all(-1).argmax(-1)
# Output as list of arrays
In [107]: [a[:i] for a,i in zip(arr_3d,idx)]
Out[107]:
[array([[1, 2, 3],
[4, 5, 6]]), array([[3, 2, 1]]), array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])]
# Output as list of lists
In [108]: [a[:i].tolist() for a,i in zip(arr_3d,idx)]
Out[108]: [[[1, 2, 3], [4, 5, 6]], [[3, 2, 1]], [[1, 2, 3], [4, 5, 6], [7, 8, 9]]]

Numpy : convert 2D array to 3D array

I have a 2 dimensional array : A = numpy.array([[1, 2, 3], [4, 5, 6]]) and would like to convert it to a 3 dimensional array : B = numpy.array([[[1, 2, 3], [4, 5, 6]]])
Is there a simple way to do that ?
Simply add a new axis at the start with np.newaxis -
import numpy as np
B = A[np.newaxis,:,:]
We could skip listing the trailing axes -
B = A[np.newaxis]
Also, bring in the alias None to replace np.newaxis for a more compact solution -
B = A[None]
It is also possible to create a new NumPy array by using the constructor so that it takes in a list. This list contains a single element which is the array A and it will allow you to create same array with the singleton dimension being the first one. The result would be the 3D array you desire:
B = numpy.array([A])
Example Output
In [13]: import numpy as np
In [14]: A = np.array([[1, 2, 3], [4, 5, 6]])
In [15]: B = np.array([A])
In [16]: B
Out[16]:
array([[[1, 2, 3],
[4, 5, 6]]])

how to convert 2d list to 2d numpy array?

I have a 2D list something like
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
and I want to convert it to a 2d numpy array. Can we do it without allocating memory like
numpy.zeros((3,3))
and then storing values to it?
Just pass the list to np.array:
a = np.array(a)
You can also take this opportunity to set the dtype if the default is not what you desire.
a = np.array(a, dtype=...)
just use following code
c = np.matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
Then it will give you
you can check shape and dimension of matrix by using following code
c.shape
c.ndim
np.array() is even more powerful than what unutbu said above.
You also could use it to convert a list of np arrays to a higher dimention array, the following is a simple example:
aArray=np.array([1,1,1])
bArray=np.array([2,2,2])
aList=[aArray, bArray]
xArray=np.array(aList)
xArray's shape is (2,3), it's a standard np array. This operation avoids a loop programming.
I am using large data sets exported to a python file in the form
XVals1 = [.........]
XVals2 = [.........]
Each list is of identical length. I use
>>> a1 = np.array(SV.XVals1)
>>> a2 = np.array(SV.XVals2)
Then
>>> A = np.matrix([a1,a2])

Categories