Python : simple array manipulation with Numpy - python

Sorry for this simple question, but I can't find how to figure it out :
I have a long 1D numpy array like:
[1,2,3,4,5,6,7,8,9,10,11,12, ... ,n1,n2,n3]
this array is used to store x y z position of points, like [x0,y0,z0,x1,y1,z1 etc.... ]
I would like to convert it to this form :
[ [1,2,3],[4,5,6],[7,8,9],[10,11,12],....,[n1,n2,n3] ]
It it possible with numpy without going through slow for loops ?
Thanks :)

Use the reshape method.
a = np.arange(27) # some 1-D numpy array
a.reshape(-1, 3)

Related

How to write a function that DIRECTLY outputs a 2D Numpy array from two 1D array?

I created two numpy 1D arrays
x1 = np.linspace(0, 1, 5)
x2 = np.linspace(0, 10, 5)
I wrote a function
def myfoo(x1,x2):
return x1**2+x1*x2+x2**2
To get a 2D numpy array, I use the following code :
y=np.empty((x1.size,x2.size))
for a in range(0,x2.size):
y[a]=myfoo(x1,x2[a])
I would like to know if is it possible to write a function that outputs this 2D array DIRECTLY. I simply wonder if is possible to write y=myfoo2(x1,x2) instead of three code lines as above.
I know I can insert these lines into the function as suggested in the comment. But, I wonder if it exists in Numpy or Python "something" (function, operators, ...) like the mathematicals dyadic product of two vectors (i.e. from two 1D vectors of size m,n, this operation gives a matrix of size m x n)
Thanks for answer
myfoo(x1[:,None], x2). x1[:,None]*x2
produces a (5,5) array.

How to retrieve the dimensions of a numpy.array

I am very new to learning python and I am trying to scale a matrix using library np. array n x m.
the question : if a matrix with using library np.array is given as input and I don't know how big the range the matrix, how can I initialize the size of m? Are there certain features or tricks in Python that can be used for this?
import numpy as np
def scaleArray(arr: np.array);
arrayB = np.array([[1,2,4],
[3,4,5],
[2,1,0],
[0,1,0]])
scaleArray(b)
This arrayB is just for example.
Expected output :
3
arr.shape is what you are looking for, it gives you the dimensions of the nD array.
In your case, you want arr.shape[1]

How to reshape numpy array of numpy arrays? [duplicate]

I'm trying to turn a list of 2d numpy arrays into a 2d numpy array. For example,
dat_list = []
for i in range(10):
dat_list.append(np.zeros([5, 10]))
What I would like to get out of this list is an array that is (50, 10). However, when I try the following, I get a (10,5,10) array.
output = np.array(dat_list)
Thoughts?
you want to stack them:
np.vstack(dat_list)
Above accepted answer is correct for 2D arrays as you requested. For 3D input arrays though, vstack() will give you a surprising outcome. For those, use stack(<list of 3D arrays>, 0).
See https://docs.scipy.org/doc/numpy/reference/generated/numpy.append.html
for details. You can use append, but will want to specify the axis on which to append.
dat_list.append(np.zeros([5, 10]),axis=0)

Numpy iterating over 3d vector array

Im trying to iterate over a Numpy Array that contains 3d numpy arrays (3d vectors) inside it.
Something like this:
import numpy as np
Matrix = np.zeros(shape=(10, 3))
# => [
[0,0,0],
[0,0,0],
...
[0,0,0]
]
I need to iterate over it, getting each 3d Vector.
In pseudo code:
for vector in Matrix
print vector #=> [0,0,0]
Is there any Numpy native way of doing this?
What is the fastest way of doing this?
Thanks!
Fran
Your pseudocode is only missing a colon:
for vector in matrix:
print vector
That said, you will generally want to avoid explicit iteration over a NumPy array. Take advantage of broadcasted operations and NumPy built-in functions as much as possible; it moves the loops into C instead of interpreted Python, and it tends to produce shorter code, too.

Multiple Element Indexing in multi-dimensional array

I have a 3d Numpy array and would like to take the mean over one axis considering certain elements from the other two dimensions.
This is an example code depicting my problem:
import numpy as np
myarray = np.random.random((5,10,30))
yy = [1,2,3,4]
xx = [20,21,22,23,24,25,26,27,28,29]
mymean = [ np.mean(myarray[t,yy,xx]) for t in np.arange(5) ]
However, this results in:
ValueError: shape mismatch: objects cannot be broadcast to a single shape
Why does an indexing like e.g. myarray[:,[1,2,3,4],[1,2,3,4]] work, but not my code above?
This is how you fancy-index over more than one dimension:
>>> np.mean(myarray[np.arange(5)[:, None, None], np.array(yy)[:, None], xx],
axis=(-1, -2))
array([ 0.49482768, 0.53013301, 0.4485054 , 0.49516017, 0.47034123])
When you use fancy indexing, i.e. a list or array as an index, over more than one dimension, numpy broadcasts those arrays to a common shape, and uses them to index the array. You need to add those extra dimensions of length 1 at the end of the first indexing arrays, for the broadcast to work properly. Here are the rules of the game.
Since you use consecutive elements you can use a slice:
import numpy as np
myarray = np.random.random((5,10,30))
yy = slice(1,5)
xx = slice(20, 30)
mymean = [np.mean(myarray[t, yy, xx]) for t in np.arange(5)]
To answer your question about why it doesn't work: when you use lists/arrays as indices, Numpy uses a different set of indexing semantics than it does if you use slices. You can see the full story in the documentation and, as that page says, it "can be somewhat mind-boggling".
If you want to do it for nonconsecutive elements, you must grok that complex indexing mechanism.

Categories