cloud

Python Numpy

arange()

The syntax of arange:
arange([start,] stop[, step,], dtype=None)

Example 1:

>>> import numpy as np
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])


Example 2:

>>> import numpy as np
>>> a = np.arange(10).reshape(5,2)
>>> a
array([[0, 1],
[2, 3],
[4, 5],
[6, 7],
[8, 9]])
>>> a = np.arange(10).reshape(5,2)
>>>

Let us take different examples with its shapes.
>>> import numpy as np
>>> a = np.arange(10).reshape(4,2)
Traceback (most recent call last):
File "", line 1, in
ValueError: total size of new array must be unchanged
>>>

Example 3

Let us do more experiment with arange() by taking start and end point
>>> import numpy as np
>>> a
array([4])
>>> a = np.arange(4,10)
>>> a
array([4, 5, 6, 7, 8, 9])
>>> a = np.arange(4,10,2)
>>> a
array([4, 6, 8])


In above example array of 10 can not be reshaped in 4,2 dimession.

Slicing and indexing multidimensional arrays

The ndarray (n-dimensional array) class supports slicing over multiple dimensions.
To illustrate, create an array with the arange() function and reshape it:
>>> import numpy as np
>>> k= np.arange(12).reshape(6,2)
>>> k
array([[ 0, 1],
[ 2, 3],
[ 4, 5],
[ 6, 7],
[ 8, 9],
[10, 11]])

First Element of First Row and First Column
>>> k[0,0]
0


First Element of all Rows
>>> k[:,0]
array([ 0, 2, 4, 6, 8, 10])


Second Element of all Rows
>>> k[:,1]
array([ 1, 3, 5, 7, 9, 11])


First element from all columns
>>> k[0,:]
array([0, 1])


Mulplication of Array

>>> import numpy as np
>>> k= np.arange(9).reshape(3,3)
>>> k
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> k*2
array([[ 0, 2, 4],
[ 6, 8, 10],
[12, 14, 16]])

Matrix multiplication

>>> import numpy as np
>>> A= np.array([[3,4],[5,6]])
>>> B= np.array([[7,8],[1,3]])
>>> A*B
array([[21, 32],
[ 5, 18]])


Creating a multidimensional array

Create a two-by-two array:
>>> import numpy as np
>>> m = np.array([np.arange(2), np.arange(2)])
>>> m
array([[0, 1],
[0, 1]])







admin