Download as pdf or txt
Download as pdf or txt
You are on page 1of 48

In [2]: import numpy as np

Create a numpy array


In [2]: np.array([10,20,30,40])

Out[2]: array([10, 20, 30, 40])

In [3]: a = np.array([10,20,30,40])
a.ndim #check dimension of array

Out[3]: 1

In [6]: # what is the type of numpy array


type(a)

Out[6]: numpy.ndarray

In [4]: np.array([[1,2,3],[4,5,6]])

Out[4]: array([[1, 2, 3],


[4, 5, 6]])

In [5]: np.array([[1,2,3],[4,5,6]]).ndim

Out[5]: 2

In [7]: np.array([[[1,2],[3,4]],[[6,7],[8,9]]])

Out[7]: array([[[1, 2],


[3, 4]],

[[6, 7],
[8, 9]]])

In [8]: np.array([[[1,2],[3,4]],[[6,7],[8,9]]]).ndim

Out[8]: 3

Check some properties of an array`


In [9]: ar = np.array([[[1,2],[3,4]],[[6,7],[8,9]]])
ar

Out[9]: array([[[1, 2],


[3, 4]],

[[6, 7],
[8, 9]]])

Heading
In [26]: # check dim
ar.ndim

Out[26]: 3

In [22]: # check total blocks , rows and colums


ar.shape #(2: blocks, 2:rows, 2:columns)

Out[22]: (2, 2, 2)

In [27]: # if i want to check total number of elements


ar.size

Out[27]: 8

In [44]: len(ar)

Out[44]: 2

In [47]: d = np.array([[1,2]])
d

Out[47]: array([[1, 2]])

In [50]: d.shape

Out[50]: (1, 2)

In [51]: len(d)

Out[51]: 1

In [52]: len(d.ravel())

Out[52]: 2

In [30]: #how much bytes alocated to each element


ar.itemsize

Out[30]: 4

In [31]: # check memory address in hex


ar.data

Out[31]: <memory at 0x000002A97A1EE6D0>

In [32]: ar

Out[32]: array([[[1, 2],


[3, 4]],

[[6, 7],
[8, 9]]])
In [33]: print(ar)

[[[1 2]
[3 4]]

[[6 7]
[8 9]]]

In [38]: a = 10
b = 20
print(a)
b

10

Out[38]: 20

Creation of numpy array using numpy functions


In [54]: # array of all 0's
np.zeros(10)

Out[54]: array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])

In [55]: # 2D array of 0's


np.zeros((3,3))

Out[55]: array([[0., 0., 0.],


[0., 0., 0.],
[0., 0., 0.]])

In [57]: #lets change dtype


np.zeros((3,3),dtype=int)

Out[57]: dtype('int32')

In [58]: np.zeros((3,3),dtype='int64')

Out[58]: array([[0, 0, 0],


[0, 0, 0],
[0, 0, 0]], dtype=int64)

In [68]: np.zeros((3,3),dtype=np.int32)

Out[68]: array([[0, 0, 0],


[0, 0, 0],
[0, 0, 0]])

In [64]: #check the difference between them


x = np.zeros((3,3),dtype=int)
y = np.zeros((3,3),dtype='int8')

In [60]: x.itemsize

Out[60]: 4
In [61]: x.__sizeof__()

Out[61]: 156

In [65]: y.itemsize

Out[65]: 1

In [66]: y.__sizeof__()

Out[66]: 129

In [69]: # 32 bit consumes more memory than 8 bits

In [70]: # if i want array with all 1's


np.ones(20)

Out[70]: array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
1., 1., 1.])

In [71]: np.ones((4,3))

Out[71]: array([[1., 1., 1.],


[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])

In [74]: # if i want array with specified value


np.full(4,fill_value=99)

Out[74]: array([99, 99, 99, 99])

In [75]: np.full((3,3,3),fill_value=99)

Out[75]: array([[[99, 99, 99],


[99, 99, 99],
[99, 99, 99]],

[[99, 99, 99],


[99, 99, 99],
[99, 99, 99]],

[[99, 99, 99],


[99, 99, 99],
[99, 99, 99]]])

In [85]: np.full((3,3,3),fill_value='NA')
# when we have hetro. data or str data its dtype is 'U' unicode

Out[85]: array([[['NA', 'NA', 'NA'],


['NA', 'NA', 'NA'],
['NA', 'NA', 'NA']],

[['NA', 'NA', 'NA'],


['NA', 'NA', 'NA'],
['NA', 'NA', 'NA']],

[['NA', 'NA', 'NA'],


['NA', 'NA', 'NA'],
['NA', 'NA', 'NA']]], dtype='<U2')
arange()
In [77]: # it is same as that of range in python
np.arange(11)

Out[77]: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

In [78]: # start and stop


np.arange(101,111)

Out[78]: array([101, 102, 103, 104, 105, 106, 107, 108, 109, 110])

In [79]: # start and stop , step


np.arange(1,100,2)# odd numbers

Out[79]: array([ 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33,
35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67,
69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99])

In [80]: # array with -ve steping


np.arange(110,100,-1)

Out[80]: array([110, 109, 108, 107, 106, 105, 104, 103, 102, 101])

In [82]: #we can use -ve values as well


np.arange(-10,1)

Out[82]: array([-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0])

In [83]: # create an array with values -10 to +10


np.arange(-10,11)

Out[83]: array([-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2,
3, 4, 5, 6, 7, 8, 9, 10])

In [87]: help(np)

Help on package numpy:

NAME
numpy

DESCRIPTION
NumPy
=====

Provides
1. An array object of arbitrary homogeneous items
2. Fast mathematical operations over arrays
3. Linear Algebra, Fourier Transforms, Random Number Generation

How to use the documentation


----------------------------
Documentation is available in two forms: docstrings provided
with the code, and a loose standing reference guide, available from
`the NumPy homepage <https://www.scipy.org>`_.
In [88]: # if we want information about numpy and its functions
help(np.arange)
Help on built-in function arange in module numpy:

arange(...)
arange([start,] stop[, step,], dtype=None, *, like=None)

Return evenly spaced values within a given interval.

Values are generated within the half-open interval ``[start, stop)``


(in other words, the interval including `start` but excluding `stop`).
For integer arguments the function is equivalent to the Python built-in
`range` function, but returns an ndarray rather than a list.

When using a non-integer step, such as 0.1, the results will often not
be consistent. It is better to use `numpy.linspace` for these cases.

Parameters
----------
start : integer or real, optional
Start of interval. The interval includes this value. The default
start value is 0.
stop : integer or real
End of interval. The interval does not include this value, except
in some cases where `step` is not an integer and floating point
round-off affects the length of `out`.
step : integer or real, optional
Spacing between values. For any output `out`, this is the distance
between two adjacent values, ``out[i+1] - out[i]``. The default
step size is 1. If `step` is specified as a position argument,
`start` must also be given.
dtype : dtype
The type of the output array. If `dtype` is not given, infer the data
type from the other input arguments.
like : array_like
Reference object to allow the creation of arrays which are not
NumPy arrays. If an array-like passed in as ``like`` supports
the ``__array_function__`` protocol, the result will be defined
by it. In this case, it ensures the creation of an array object
compatible with that passed in via this argument.

.. note::
The ``like`` keyword is an experimental feature pending on
acceptance of :ref:`NEP 35 <NEP35>`.

.. versionadded:: 1.20.0

Returns
-------
arange : ndarray
Array of evenly spaced values.

For floating point arguments, the length of the result is


``ceil((stop - start)/step)``. Because of floating point overflow,
this rule may result in the last element of `out` being greater
than `stop`.

See Also
--------
numpy.linspace : Evenly spaced numbers with careful handling of endpoints.
numpy.ogrid: Arrays of evenly spaced numbers in N-dimensions.
numpy.mgrid: Grid-shaped arrays of evenly spaced numbers in N-dimensions.

Examples
--------
>>> np.arange(3)
array([0, 1, 2])
>>> np.arange(3.0)
array([ 0., 1., 2.])
>>> np.arange(3,7)
array([3, 4, 5, 6])
>>> np.arange(3,7,2)
array([3, 5])
In [90]: np.info(np.arange)
arange([start,] stop[, step,], dtype=None, *, like=None)

Return evenly spaced values within a given interval.

Values are generated within the half-open interval ``[start, stop)``


(in other words, the interval including `start` but excluding `stop`).
For integer arguments the function is equivalent to the Python built-in
`range` function, but returns an ndarray rather than a list.

When using a non-integer step, such as 0.1, the results will often not
be consistent. It is better to use `numpy.linspace` for these cases.

Parameters
----------
start : integer or real, optional
Start of interval. The interval includes this value. The default
start value is 0.
stop : integer or real
End of interval. The interval does not include this value, except
in some cases where `step` is not an integer and floating point
round-off affects the length of `out`.
step : integer or real, optional
Spacing between values. For any output `out`, this is the distance
between two adjacent values, ``out[i+1] - out[i]``. The default
step size is 1. If `step` is specified as a position argument,
`start` must also be given.
dtype : dtype
The type of the output array. If `dtype` is not given, infer the data
type from the other input arguments.
like : array_like
Reference object to allow the creation of arrays which are not
NumPy arrays. If an array-like passed in as ``like`` supports
the ``__array_function__`` protocol, the result will be defined
by it. In this case, it ensures the creation of an array object
compatible with that passed in via this argument.

.. note::
The ``like`` keyword is an experimental feature pending on
acceptance of :ref:`NEP 35 <NEP35>`.

.. versionadded:: 1.20.0

Returns
-------
arange : ndarray
Array of evenly spaced values.

For floating point arguments, the length of the result is


``ceil((stop - start)/step)``. Because of floating point overflow,
this rule may result in the last element of `out` being greater
than `stop`.

See Also
--------
numpy.linspace : Evenly spaced numbers with careful handling of endpoints.
numpy.ogrid: Arrays of evenly spaced numbers in N-dimensions.
numpy.mgrid: Grid-shaped arrays of evenly spaced numbers in N-dimensions.

Examples
--------
>>> np.arange(3)
array([0, 1, 2])
>>> np.arange(3.0)
array([ 0., 1., 2.])
>>> np.arange(3,7)
array([3, 4, 5, 6])
>>> np.arange(3,7,2)
array([3, 5])

In [92]: np.arange?

In [ ]: #or use shift + tab

np.linspace
In [ ]: # used to generate linearly spaced values
# with homogeneous spacing
# equal spacing btween 2 consecutive elements

In [94]: '''
start,
stop,
num=50,
endpoint=True,
retstep=False,
dtype=None,
axis=0,
'''
np.linspace(2,11) #default 50 values it will generate

Out[94]: array([ 2. , 2.18367347, 2.36734694, 2.55102041, 2.73469388,


2.91836735, 3.10204082, 3.28571429, 3.46938776, 3.65306122,
3.83673469, 4.02040816, 4.20408163, 4.3877551 , 4.57142857,
4.75510204, 4.93877551, 5.12244898, 5.30612245, 5.48979592,
5.67346939, 5.85714286, 6.04081633, 6.2244898 , 6.40816327,
6.59183673, 6.7755102 , 6.95918367, 7.14285714, 7.32653061,
7.51020408, 7.69387755, 7.87755102, 8.06122449, 8.24489796,
8.42857143, 8.6122449 , 8.79591837, 8.97959184, 9.16326531,
9.34693878, 9.53061224, 9.71428571, 9.89795918, 10.08163265,
10.26530612, 10.44897959, 10.63265306, 10.81632653, 11. ])

In [95]: np.linspace(2,11,num=20)

Out[95]: array([ 2. , 2.47368421, 2.94736842, 3.42105263, 3.89473684,


4.36842105, 4.84210526, 5.31578947, 5.78947368, 6.26315789,
6.73684211, 7.21052632, 7.68421053, 8.15789474, 8.63157895,
9.10526316, 9.57894737, 10.05263158, 10.52631579, 11. ])

In [98]: 2 - 2.47368421

Out[98]: -0.47368421000000005

In [97]: 2.47368421- 2.94736842 #difference value is constant

Out[97]: -0.47368421000000005

In [99]: #u want to check difference


np.linspace(2,11,num=20,retstep=True)

Out[99]: (array([ 2. , 2.47368421, 2.94736842, 3.42105263, 3.89473684,


4.36842105, 4.84210526, 5.31578947, 5.78947368, 6.26315789,
6.73684211, 7.21052632, 7.68421053, 8.15789474, 8.63157895,
9.10526316, 9.57894737, 10.05263158, 10.52631579, 11. ]),
0.47368421052631576)
In [100]: np.linspace(2,11,num=20,retstep=True,endpoint = False) #stop will be exclusive

Out[100]: (array([ 2. , 2.45, 2.9 , 3.35, 3.8 , 4.25, 4.7 , 5.15, 5.6 ,
6.05, 6.5 , 6.95, 7.4 , 7.85, 8.3 , 8.75, 9.2 , 9.65,
10.1 , 10.55]),
0.45)

In [101]: # -10 to +10


np.linspace(-10,10,num = 21)

Out[101]: array([-10., -9., -8., -7., -6., -5., -4., -3., -2., -1., 0.,
1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])

In [103]: np.linspace(-10,11,num = 21,endpoint=False)

Out[103]: array([-10., -9., -8., -7., -6., -5., -4., -3., -2., -1., 0.,
1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])

In [3]: np.linspace(-10,11,num = 21)

Out[3]: array([-10. , -8.95, -7.9 , -6.85, -5.8 , -4.75, -3.7 , -2.65,


-1.6 , -0.55, 0.5 , 1.55, 2.6 , 3.65, 4.7 , 5.75,
6.8 , 7.85, 8.9 , 9.95, 11. ])

In [4]: np.linspace(-10,11,num = 21).ndim

Out[4]: 1

In [5]: np.linspace(-10,11,num = 21).shape

Out[5]: (21,)

In [6]: type(np.linspace(-10,11,num = 21))

Out[6]: numpy.ndarray

In [7]: np.arange(1,100,2)

Out[7]: array([ 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33,
35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67,
69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99])

In [8]: np.arange(2,100,2)

Out[8]: array([ 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34,
36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68,
70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98])

In [9]: np.arange(-10,11)

Out[9]: array([-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2,
3, 4, 5, 6, 7, 8, 9, 10])

In [ ]: ​
In [2]: import numpy as np

Create a numpy array


In [2]: np.array([10,20,30,40])

Out[2]: array([10, 20, 30, 40])

In [3]: a = np.array([10,20,30,40])
a.ndim #check dimension of array

Out[3]: 1

In [6]: # what is the type of numpy array


type(a)

Out[6]: numpy.ndarray

In [4]: np.array([[1,2,3],[4,5,6]])

Out[4]: array([[1, 2, 3],


[4, 5, 6]])

In [5]: np.array([[1,2,3],[4,5,6]]).ndim

Out[5]: 2

In [7]: np.array([[[1,2],[3,4]],[[6,7],[8,9]]])

Out[7]: array([[[1, 2],


[3, 4]],

[[6, 7],
[8, 9]]])

In [8]: np.array([[[1,2],[3,4]],[[6,7],[8,9]]]).ndim

Out[8]: 3

Check some properties of an array`


In [9]: ar = np.array([[[1,2],[3,4]],[[6,7],[8,9]]])
ar

Out[9]: array([[[1, 2],


[3, 4]],

[[6, 7],
[8, 9]]])

Heading
In [26]: # check dim
ar.ndim

Out[26]: 3

In [22]: # check total blocks , rows and colums


ar.shape #(2: blocks, 2:rows, 2:columns)

Out[22]: (2, 2, 2)

In [27]: # if i want to check total number of elements


ar.size

Out[27]: 8

In [44]: len(ar)

Out[44]: 2

In [47]: d = np.array([[1,2]])
d

Out[47]: array([[1, 2]])

In [50]: d.shape

Out[50]: (1, 2)

In [51]: len(d)

Out[51]: 1

In [52]: len(d.ravel())

Out[52]: 2

In [30]: #how much bytes alocated to each element


ar.itemsize

Out[30]: 4

In [31]: # check memory address in hex


ar.data

Out[31]: <memory at 0x000002A97A1EE6D0>

In [32]: ar

Out[32]: array([[[1, 2],


[3, 4]],

[[6, 7],
[8, 9]]])
In [33]: print(ar)

[[[1 2]
[3 4]]

[[6 7]
[8 9]]]

In [38]: a = 10
b = 20
print(a)
b

10

Out[38]: 20

Creation of numpy array using numpy functions


In [54]: # array of all 0's
np.zeros(10)

Out[54]: array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])

In [55]: # 2D array of 0's


np.zeros((3,3))

Out[55]: array([[0., 0., 0.],


[0., 0., 0.],
[0., 0., 0.]])

In [57]: #lets change dtype


np.zeros((3,3),dtype=int)

Out[57]: dtype('int32')

In [58]: np.zeros((3,3),dtype='int64')

Out[58]: array([[0, 0, 0],


[0, 0, 0],
[0, 0, 0]], dtype=int64)

In [68]: np.zeros((3,3),dtype=np.int32)

Out[68]: array([[0, 0, 0],


[0, 0, 0],
[0, 0, 0]])

In [64]: #check the difference between them


x = np.zeros((3,3),dtype=int)
y = np.zeros((3,3),dtype='int8')

In [60]: x.itemsize

Out[60]: 4
In [61]: x.__sizeof__()

Out[61]: 156

In [65]: y.itemsize

Out[65]: 1

In [66]: y.__sizeof__()

Out[66]: 129

In [69]: # 32 bit consumes more memory than 8 bits

In [70]: # if i want array with all 1's


np.ones(20)

Out[70]: array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
1., 1., 1.])

In [71]: np.ones((4,3))

Out[71]: array([[1., 1., 1.],


[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])

In [74]: # if i want array with specified value


np.full(4,fill_value=99)

Out[74]: array([99, 99, 99, 99])

In [75]: np.full((3,3,3),fill_value=99)

Out[75]: array([[[99, 99, 99],


[99, 99, 99],
[99, 99, 99]],

[[99, 99, 99],


[99, 99, 99],
[99, 99, 99]],

[[99, 99, 99],


[99, 99, 99],
[99, 99, 99]]])

In [85]: np.full((3,3,3),fill_value='NA')
# when we have hetro. data or str data its dtype is 'U' unicode

Out[85]: array([[['NA', 'NA', 'NA'],


['NA', 'NA', 'NA'],
['NA', 'NA', 'NA']],

[['NA', 'NA', 'NA'],


['NA', 'NA', 'NA'],
['NA', 'NA', 'NA']],

[['NA', 'NA', 'NA'],


['NA', 'NA', 'NA'],
['NA', 'NA', 'NA']]], dtype='<U2')
arange()
In [77]: # it is same as that of range in python
np.arange(11)

Out[77]: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

In [78]: # start and stop


np.arange(101,111)

Out[78]: array([101, 102, 103, 104, 105, 106, 107, 108, 109, 110])

In [79]: # start and stop , step


np.arange(1,100,2)# odd numbers

Out[79]: array([ 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33,
35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67,
69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99])

In [80]: # array with -ve steping


np.arange(110,100,-1)

Out[80]: array([110, 109, 108, 107, 106, 105, 104, 103, 102, 101])

In [82]: #we can use -ve values as well


np.arange(-10,1)

Out[82]: array([-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0])

In [83]: # create an array with values -10 to +10


np.arange(-10,11)

Out[83]: array([-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2,
3, 4, 5, 6, 7, 8, 9, 10])

In [87]: help(np)

Help on package numpy:

NAME
numpy

DESCRIPTION
NumPy
=====

Provides
1. An array object of arbitrary homogeneous items
2. Fast mathematical operations over arrays
3. Linear Algebra, Fourier Transforms, Random Number Generation

How to use the documentation


----------------------------
Documentation is available in two forms: docstrings provided
with the code, and a loose standing reference guide, available from
`the NumPy homepage <https://www.scipy.org>`_.
In [88]: # if we want information about numpy and its functions
help(np.arange)
Help on built-in function arange in module numpy:

arange(...)
arange([start,] stop[, step,], dtype=None, *, like=None)

Return evenly spaced values within a given interval.

Values are generated within the half-open interval ``[start, stop)``


(in other words, the interval including `start` but excluding `stop`).
For integer arguments the function is equivalent to the Python built-in
`range` function, but returns an ndarray rather than a list.

When using a non-integer step, such as 0.1, the results will often not
be consistent. It is better to use `numpy.linspace` for these cases.

Parameters
----------
start : integer or real, optional
Start of interval. The interval includes this value. The default
start value is 0.
stop : integer or real
End of interval. The interval does not include this value, except
in some cases where `step` is not an integer and floating point
round-off affects the length of `out`.
step : integer or real, optional
Spacing between values. For any output `out`, this is the distance
between two adjacent values, ``out[i+1] - out[i]``. The default
step size is 1. If `step` is specified as a position argument,
`start` must also be given.
dtype : dtype
The type of the output array. If `dtype` is not given, infer the data
type from the other input arguments.
like : array_like
Reference object to allow the creation of arrays which are not
NumPy arrays. If an array-like passed in as ``like`` supports
the ``__array_function__`` protocol, the result will be defined
by it. In this case, it ensures the creation of an array object
compatible with that passed in via this argument.

.. note::
The ``like`` keyword is an experimental feature pending on
acceptance of :ref:`NEP 35 <NEP35>`.

.. versionadded:: 1.20.0

Returns
-------
arange : ndarray
Array of evenly spaced values.

For floating point arguments, the length of the result is


``ceil((stop - start)/step)``. Because of floating point overflow,
this rule may result in the last element of `out` being greater
than `stop`.

See Also
--------
numpy.linspace : Evenly spaced numbers with careful handling of endpoints.
numpy.ogrid: Arrays of evenly spaced numbers in N-dimensions.
numpy.mgrid: Grid-shaped arrays of evenly spaced numbers in N-dimensions.

Examples
--------
>>> np.arange(3)
array([0, 1, 2])
>>> np.arange(3.0)
array([ 0., 1., 2.])
>>> np.arange(3,7)
array([3, 4, 5, 6])
>>> np.arange(3,7,2)
array([3, 5])
In [90]: np.info(np.arange)
arange([start,] stop[, step,], dtype=None, *, like=None)

Return evenly spaced values within a given interval.

Values are generated within the half-open interval ``[start, stop)``


(in other words, the interval including `start` but excluding `stop`).
For integer arguments the function is equivalent to the Python built-in
`range` function, but returns an ndarray rather than a list.

When using a non-integer step, such as 0.1, the results will often not
be consistent. It is better to use `numpy.linspace` for these cases.

Parameters
----------
start : integer or real, optional
Start of interval. The interval includes this value. The default
start value is 0.
stop : integer or real
End of interval. The interval does not include this value, except
in some cases where `step` is not an integer and floating point
round-off affects the length of `out`.
step : integer or real, optional
Spacing between values. For any output `out`, this is the distance
between two adjacent values, ``out[i+1] - out[i]``. The default
step size is 1. If `step` is specified as a position argument,
`start` must also be given.
dtype : dtype
The type of the output array. If `dtype` is not given, infer the data
type from the other input arguments.
like : array_like
Reference object to allow the creation of arrays which are not
NumPy arrays. If an array-like passed in as ``like`` supports
the ``__array_function__`` protocol, the result will be defined
by it. In this case, it ensures the creation of an array object
compatible with that passed in via this argument.

.. note::
The ``like`` keyword is an experimental feature pending on
acceptance of :ref:`NEP 35 <NEP35>`.

.. versionadded:: 1.20.0

Returns
-------
arange : ndarray
Array of evenly spaced values.

For floating point arguments, the length of the result is


``ceil((stop - start)/step)``. Because of floating point overflow,
this rule may result in the last element of `out` being greater
than `stop`.

See Also
--------
numpy.linspace : Evenly spaced numbers with careful handling of endpoints.
numpy.ogrid: Arrays of evenly spaced numbers in N-dimensions.
numpy.mgrid: Grid-shaped arrays of evenly spaced numbers in N-dimensions.

Examples
--------
>>> np.arange(3)
array([0, 1, 2])
>>> np.arange(3.0)
array([ 0., 1., 2.])
>>> np.arange(3,7)
array([3, 4, 5, 6])
>>> np.arange(3,7,2)
array([3, 5])

In [92]: np.arange?

In [ ]: #or use shift + tab

np.linspace
In [ ]: # used to generate linearly spaced values
# with homogeneous spacing
# equal spacing btween 2 consecutive elements

In [94]: '''
start,
stop,
num=50,
endpoint=True,
retstep=False,
dtype=None,
axis=0,
'''
np.linspace(2,11) #default 50 values it will generate

Out[94]: array([ 2. , 2.18367347, 2.36734694, 2.55102041, 2.73469388,


2.91836735, 3.10204082, 3.28571429, 3.46938776, 3.65306122,
3.83673469, 4.02040816, 4.20408163, 4.3877551 , 4.57142857,
4.75510204, 4.93877551, 5.12244898, 5.30612245, 5.48979592,
5.67346939, 5.85714286, 6.04081633, 6.2244898 , 6.40816327,
6.59183673, 6.7755102 , 6.95918367, 7.14285714, 7.32653061,
7.51020408, 7.69387755, 7.87755102, 8.06122449, 8.24489796,
8.42857143, 8.6122449 , 8.79591837, 8.97959184, 9.16326531,
9.34693878, 9.53061224, 9.71428571, 9.89795918, 10.08163265,
10.26530612, 10.44897959, 10.63265306, 10.81632653, 11. ])

In [95]: np.linspace(2,11,num=20)

Out[95]: array([ 2. , 2.47368421, 2.94736842, 3.42105263, 3.89473684,


4.36842105, 4.84210526, 5.31578947, 5.78947368, 6.26315789,
6.73684211, 7.21052632, 7.68421053, 8.15789474, 8.63157895,
9.10526316, 9.57894737, 10.05263158, 10.52631579, 11. ])

In [98]: 2 - 2.47368421

Out[98]: -0.47368421000000005

In [97]: 2.47368421- 2.94736842 #difference value is constant

Out[97]: -0.47368421000000005

In [99]: #u want to check difference


np.linspace(2,11,num=20,retstep=True)

Out[99]: (array([ 2. , 2.47368421, 2.94736842, 3.42105263, 3.89473684,


4.36842105, 4.84210526, 5.31578947, 5.78947368, 6.26315789,
6.73684211, 7.21052632, 7.68421053, 8.15789474, 8.63157895,
9.10526316, 9.57894737, 10.05263158, 10.52631579, 11. ]),
0.47368421052631576)
In [100]: np.linspace(2,11,num=20,retstep=True,endpoint = False) #stop will be exclusive

Out[100]: (array([ 2. , 2.45, 2.9 , 3.35, 3.8 , 4.25, 4.7 , 5.15, 5.6 ,
6.05, 6.5 , 6.95, 7.4 , 7.85, 8.3 , 8.75, 9.2 , 9.65,
10.1 , 10.55]),
0.45)

In [101]: # -10 to +10


np.linspace(-10,10,num = 21)

Out[101]: array([-10., -9., -8., -7., -6., -5., -4., -3., -2., -1., 0.,
1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])

In [103]: np.linspace(-10,11,num = 21,endpoint=False)

Out[103]: array([-10., -9., -8., -7., -6., -5., -4., -3., -2., -1., 0.,
1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])

In [3]: np.linspace(-10,11,num = 21)

Out[3]: array([-10. , -8.95, -7.9 , -6.85, -5.8 , -4.75, -3.7 , -2.65,


-1.6 , -0.55, 0.5 , 1.55, 2.6 , 3.65, 4.7 , 5.75,
6.8 , 7.85, 8.9 , 9.95, 11. ])

In [4]: np.linspace(-10,11,num = 21).ndim

Out[4]: 1

In [5]: np.linspace(-10,11,num = 21).shape

Out[5]: (21,)

In [6]: type(np.linspace(-10,11,num = 21))

Out[6]: numpy.ndarray

In [7]: np.arange(1,100,2)

Out[7]: array([ 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33,
35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67,
69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99])

In [8]: np.arange(2,100,2)

Out[8]: array([ 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34,
36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68,
70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98])

In [9]: np.arange(-10,11)

Out[9]: array([-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2,
3, 4, 5, 6, 7, 8, 9, 10])

In [ ]: ​
In [1]: import numpy as np

In [4]: # simplest way to change shape


a = np.arange(2,26)
a

Out[4]: array([ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
19, 20, 21, 22, 23, 24, 25])

In [5]: a.shape

Out[5]: (24,)

In [6]: a.shape = (6,4) #inplace

In [7]: a

Out[7]: array([[ 2, 3, 4, 5],


[ 6, 7, 8, 9],
[10, 11, 12, 13],
[14, 15, 16, 17],
[18, 19, 20, 21],
[22, 23, 24, 25]])

Indexing and slicing


In [8]: a

Out[8]: array([[ 2, 3, 4, 5],


[ 6, 7, 8, 9],
[10, 11, 12, 13],
[14, 15, 16, 17],
[18, 19, 20, 21],
[22, 23, 24, 25]])

In [9]: # when ur array is 2D indexing work on rows default


a[0]

Out[9]: array([2, 3, 4, 5])

In [10]: a[-1]

Out[10]: array([22, 23, 24, 25])

In [11]: # i want to change value of an element from a row


# Example 25==> 50
a

Out[11]: array([[ 2, 3, 4, 5],


[ 6, 7, 8, 9],
[10, 11, 12, 13],
[14, 15, 16, 17],
[18, 19, 20, 21],
[22, 23, 24, 25]])
In [16]: #a[5] #access row first
#a[-1][3]
#a[-1][-1]
a[-1,-1]

Out[16]: 25

In [18]: # after accessing element the replace


a[-1,-1] = 50

In [19]: a

Out[19]: array([[ 2, 3, 4, 5],


[ 6, 7, 8, 9],
[10, 11, 12, 13],
[14, 15, 16, 17],
[18, 19, 20, 21],
[22, 23, 24, 50]])

In [20]: # replace elements of any row


# replace all elements by 20
a[3]

Out[20]: array([14, 15, 16, 17])

In [21]: a[3] = 20

In [22]: a

Out[22]: array([[ 2, 3, 4, 5],


[ 6, 7, 8, 9],
[10, 11, 12, 13],
[20, 20, 20, 20],
[18, 19, 20, 21],
[22, 23, 24, 50]])

In [23]: # revert this row of 20 into [1,2,3,4]


a[3]

Out[23]: array([20, 20, 20, 20])

In [24]: a[3] = [1,2,3,4]

In [25]: a

Out[25]: array([[ 2, 3, 4, 5],


[ 6, 7, 8, 9],
[10, 11, 12, 13],
[ 1, 2, 3, 4],
[18, 19, 20, 21],
[22, 23, 24, 50]])

In [26]: # if we try to convert/replace int by str


a[0,0]

Out[26]: 2
In [27]: a[0,0]= 'python'

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_10588/740517320.py in <module>
----> 1 a[0,0]= 'python'

ValueError: invalid literal for int() with base 10: 'python'

In [28]: a.dtype # as dtype is int hence we are unable to replace int by str

Out[28]: dtype('int32')

Slicing

In [30]: a

Out[30]: array([[ 2, 3, 4, 5],


[ 6, 7, 8, 9],
[10, 11, 12, 13],
[ 1, 2, 3, 4],
[18, 19, 20, 21],
[22, 23, 24, 50]])

# if we want to work on row + columns as wel then use slicing


# when we want to access multiple elements then we have slicing

In [33]: # all rows and 1st 2 columns


a[:,:2]#[row,column]

Out[33]: array([[ 2, 3],


[ 6, 7],
[10, 11],
[ 1, 2],
[18, 19],
[22, 23]])

In [36]: # fetch last 2 columns with all rows


#a[:,2:]
a[:,-2:]

Out[36]: array([[ 4, 5],


[ 8, 9],
[12, 13],
[ 3, 4],
[20, 21],
[24, 50]])

In [39]: # reverse columns


a[:,::-1]

Out[39]: array([[ 5, 4, 3, 2],


[ 9, 8, 7, 6],
[13, 12, 11, 10],
[ 4, 3, 2, 1],
[21, 20, 19, 18],
[50, 24, 23, 22]])
In [42]: # select columns starting with 2 and 5
a[:,::3]

Out[42]: array([[ 2, 5],


[ 6, 9],
[10, 13],
[ 1, 4],
[18, 21],
[22, 50]])

Now if we want to work on rows and columns together

In [43]: a

Out[43]: array([[ 2, 3, 4, 5],


[ 6, 7, 8, 9],
[10, 11, 12, 13],
[ 1, 2, 3, 4],
[18, 19, 20, 21],
[22, 23, 24, 50]])

In [46]: # access 4,5 and 8,9


a[:2,2:]

Out[46]: array([[4, 5],


[8, 9]])

In [49]: """
[11, 12],
[2, 3],
[19, 20],
"""
a[2:-1,1:-1]

Out[49]: array([[11, 12],


[ 2, 3],
[19, 20]])

In [53]: """
[18, 19]
[22,23]
"""
a[4:,:2]

Out[53]: array([[18, 19],


[22, 23]])

In [58]: """
3, 4,
23,24
"""
a[::5,1:-1]

Out[58]: array([[ 3, 4],


[23, 24]])
In [60]: # access corner elements: 2,5,22,50
a[::5,::3]

Out[60]: array([[ 2, 5],


[22, 50]])

In [61]: a.shape

Out[61]: (6, 4)

In [64]: # now lets try to replace values of an array


# replace all corner elements by 0
a[::5,::3] = 0

In [65]: a

Out[65]: array([[ 0, 3, 4, 0],


[ 6, 7, 8, 9],
[10, 11, 12, 13],
[ 1, 2, 3, 4],
[18, 19, 20, 21],
[ 0, 23, 24, 0]])

In [68]: """
[11, 12, 13],
[2, 3, 4],
------------------
replace
[10,20,30]
[50,40,30]
"""
a[2:-2,1:]

Out[68]: array([[11, 12, 13],


[ 2, 3, 4]])

In [69]: a[2:-2,1:] = [[10,20,30],[50,40,30]]

In [70]: a

Out[70]: array([[ 0, 3, 4, 0],


[ 6, 7, 8, 9],
[10, 10, 20, 30],
[ 1, 50, 40, 30],
[18, 19, 20, 21],
[ 0, 23, 24, 0]])

In [72]: # 3,4,7,8 replace like 1,2,3,4 in anticlockwise direction


a[:2,1:-1]

Out[72]: array([[3, 4],


[7, 8]])

In [73]: a[:2,1:-1] = [[1, 4],[2, 3]]


In [74]: a

Out[74]: array([[ 0, 1, 4, 0],


[ 6, 2, 3, 9],
[10, 10, 20, 30],
[ 1, 50, 40, 30],
[18, 19, 20, 21],
[ 0, 23, 24, 0]])

Interview Questions
In [79]: # i want 5 x 5 array with all values set to True
np.ones((5,5),dtype='bool')

Out[79]: array([[ True, True, True, True, True],


[ True, True, True, True, True],
[ True, True, True, True, True],
[ True, True, True, True, True],
[ True, True, True, True, True]])

In [77]: int(True)

Out[77]: 1

In [78]: bool(1)

Out[78]: True

In [80]: np.full((5,5),'True')

Out[80]: array([['True', 'True', 'True', 'True', 'True'],


['True', 'True', 'True', 'True', 'True'],
['True', 'True', 'True', 'True', 'True'],
['True', 'True', 'True', 'True', 'True'],
['True', 'True', 'True', 'True', 'True']], dtype='<U4')

In [82]: # I want 4x4 array with all values False


np.zeros((4,4),dtype='bool')

Out[82]: array([[False, False, False, False],


[False, False, False, False],
[False, False, False, False],
[False, False, False, False]])

In [84]: np.full((4,4),0,dtype='bool')

Out[84]: array([[False, False, False, False],


[False, False, False, False],
[False, False, False, False],
[False, False, False, False]])

In [85]: bool(0)

Out[85]: False
In [86]: # i want array with 4x4 :Diagonal elements as True and non diagonal False
np.eye(4)

Out[86]: array([[1., 0., 0., 0.],


[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]])

In [4]: a = np.eye(4,dtype='bool')
a

Out[4]: array([[ True, False, False, False],


[False, True, False, False],
[False, False, True, False],
[False, False, False, True]])

In [3]: np.identity(4,dtype='bool')

Out[3]: array([[ True, False, False, False],


[False, True, False, False],
[False, False, True, False],
[False, False, False, True]])

In [ ]: # I want diagnoal elements False and non diagonal True


In [5]: a.T

Out[5]: array([[ True, False, False, False],


[False, True, False, False],
[False, False, True, False],
[False, False, False, True]])

In [ ]: ​
In [1]: import numpy as np

In [2]: np.eye(4)

Out[2]: array([[1., 0., 0., 0.],


[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]])

In [3]: np.eye(4,dtype='bool')

Out[3]: array([[ True, False, False, False],


[False, True, False, False],
[False, False, True, False],
[False, False, False, True]])

In [4]: ~ np.eye(4,dtype='bool')

Out[4]: array([[False, True, True, True],


[ True, False, True, True],
[ True, True, False, True],
[ True, True, True, False]])

Conversion
In [9]: np.arange(4)

Out[9]: array([0, 1, 2, 3])

In [10]: #if i want to change dtype to float


np.arange(4,dtype='float')

Out[10]: array([0., 1., 2., 3.])

In [11]: # after creation of an array if we wwant to convert its data type then??
# use astype() function
a = np.arange(4)
a

Out[11]: array([0, 1, 2, 3])

In [12]: a.dtype

Out[12]: dtype('int32')

In [14]: #lets convert dtype


b = a.astype('int64')
b

Out[14]: array([0, 1, 2, 3], dtype=int64)

In [15]: b.dtype

Out[15]: dtype('int64')
In [16]: # Convert numpy into a list
a

Out[16]: array([0, 1, 2, 3])

In [17]: list(a)

Out[17]: [0, 1, 2, 3]

In [18]: a.tolist()

Out[18]: [0, 1, 2, 3]

In [23]: # difference betwee list() and .to_list()


# suppose we have 2D list
c = np.arange(1,11).reshape(2,5)
c

Out[23]: array([[ 1, 2, 3, 4, 5],


[ 6, 7, 8, 9, 10]])

In [21]: #list
list(c)

Out[21]: [array([1, 2, 3, 4, 5]), array([ 6, 7, 8, 9, 10])]

In [25]: c.tolist()

Out[25]: [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]

In [ ]: #Assignment:Differnce between List, array(python), numpy array

Adding element/Removing element


In [26]: a

Out[26]: array([0, 1, 2, 3])

append()

In [27]: np.append(a,100)

Out[27]: array([ 0, 1, 2, 3, 100])

In [29]: np.append(a,[100,400])

Out[29]: array([ 0, 1, 2, 3, 100, 400])

In [34]: np.append(a,'python') # here U mean Unicode

Out[34]: array(['0', '1', '2', '3', 'python'], dtype='<U11')

In [31]: [1,2,3,'python']

Out[31]: [1, 2, 3, 'python']


In [40]: np.array(['a','b','cdyhy'])

Out[40]: array(['a', 'b', 'cdyhy'], dtype='<U5')

In [42]: # perform append on 2D


c

Out[42]: array([[ 1, 2, 3, 4, 5],


[ 6, 7, 8, 9, 10]])

In [43]: np.append(c,[11,12,13,14,15])# it should add one row


# bcz we have nt supplied axis value it converted array to 1D and added
# elements at the end

Out[43]: array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])

In [46]: # but i want to add a row


# add axis=0
np.append(c,[[11,12,13,14,15]],axis=0)

Out[46]: array([[ 1, 2, 3, 4, 5],


[ 6, 7, 8, 9, 10],
[11, 12, 13, 14, 15]])

In [50]: # add column


np.append(c,[[100,-1],[200,-2]],axis=1)

Out[50]: array([[ 1, 2, 3, 4, 5, 100, -1],


[ 6, 7, 8, 9, 10, 200, -2]])

Insert

In [51]: a

Out[51]: array([0, 1, 2, 3])

In [52]: # it is used to insert values in between array using index


# np.insert(arr, obj(index), values, axis=None)
np.insert(a,1,800)

Out[52]: array([ 0, 800, 1, 2, 3])

In [55]: np.insert(a,1,[800,500])
# when we r passing multiple values use [] () any of option

Out[55]: array([ 0, 800, 500, 1, 2, 3])

In [56]: #2D insert


c

Out[56]: array([[ 1, 2, 3, 4, 5],


[ 6, 7, 8, 9, 10]])

In [69]: np.insert(c,2,[10,20,30,40,50],axis=0)

Out[69]: array([[ 1, 2, 3, 4, 5],


[ 6, 7, 8, 9, 10],
[10, 20, 30, 40, 50]])
In [67]: np.insert(c,2,[10,20],axis=1)

Out[67]: array([[ 1, 2, 10, 3, 4, 5],


[ 6, 7, 20, 8, 9, 10]])

Delete()

In [70]: a

Out[70]: array([0, 1, 2, 3])

In [71]: #np.delete(arr, obj, axis=None)


np.delete(a,2)

Out[71]: array([0, 1, 3])

In [72]: #2D array


c

Out[72]: array([[ 1, 2, 3, 4, 5],


[ 6, 7, 8, 9, 10]])

In [73]: np.delete(c,-1,axis=0)

Out[73]: array([[1, 2, 3, 4, 5]])

In [75]: # column
np.delete(c,-1,axis=1)

Out[75]: array([[1, 2, 3, 4],


[6, 7, 8, 9]])

In [79]: # suppose i want to delete multiple columns


np.delete(c,np.s_[-2:],axis=1)

Out[79]: array([[1, 2, 3],


[6, 7, 8]])

In [81]: np.delete(c,[0,2,3,4],axis=1)

Out[81]: array([[2],
[7]])

In [82]: c

Out[82]: array([[ 1, 2, 3, 4, 5],


[ 6, 7, 8, 9, 10]])

In [83]: np.delete(c,0)

Out[83]: array([ 2, 3, 4, 5, 6, 7, 8, 9, 10])

In [84]: # i want to work on columns


np.delete(c,0,axis=1)

Out[84]: array([[ 2, 3, 4, 5],


[ 7, 8, 9, 10]])
In [85]: c

Out[85]: array([[ 1, 2, 3, 4, 5],


[ 6, 7, 8, 9, 10]])

In [86]: np.delete(c,0,axis=0)

Out[86]: array([[ 6, 7, 8, 9, 10]])

In [87]: nm = ['Nilima','Santosh','Pradip','Anu','Rushikesh','Amit']
nm

Out[87]: ['Nilima', 'Santosh', 'Pradip', 'Anu', 'Rushikesh', 'Amit']

In [88]: np.array(nm)

Out[88]: array(['Nilima', 'Santosh', 'Pradip', 'Anu', 'Rushikesh', 'Amit'],


dtype='<U9')

In [91]: data = np.array(nm).reshape(-1,1)


data

Out[91]: array([['Nilima'],
['Santosh'],
['Pradip'],
['Anu'],
['Rushikesh'],
['Amit']], dtype='<U9')

In [93]: import pandas as pd


pd.DataFrame(data).to_csv('batch_17.csv')

In [94]: pd.DataFrame(np.array(nm).reshape(1,-1))

Out[94]: 0 1 2 3 4 5

0 Nilima Santosh Pradip Anu Rushikesh Amit

In [98]: d = pd.DataFrame({'id':['KP123-445-678','KI34-456-678','KP123-445-677']})
d

Out[98]: id

0 KP123-445-678

1 KI34-456-678

2 KP123-445-677

In [103]: ex = d[d['id'].str.startswith('KP')]
ex

Out[103]: id

0 KP123-445-678

2 KP123-445-677
In [107]: ex['id'].str.split('-')

Out[107]: 0 [KP123, 445, 678]


2 [KP123, 445, 677]
Name: id, dtype: object

In [109]: ex.apply(lambda x:ex['id'].str.split('-'))

Out[109]: id

0 [KP123, 445, 678]

2 [KP123, 445, 677]

In [112]: ex['id'].str.split('-',expand=True)[2]

Out[112]: 0 678
2 677
Name: 2, dtype: object

In [114]: ex['number'] = ex['id'].str.split('-',expand=True)[2]

C:\Users\hakim\AppData\Local\Temp/ipykernel_9364/3731713283.py:1: SettingWithCopyWar
ning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/u


ser_guide/indexing.html#returning-a-view-versus-a-copy (https://pandas.pydata.org/pa
ndas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy)
ex['number'] = ex['id'].str.split('-',expand=True)[2]

In [115]: ex

Out[115]: id number

0 KP123-445-678 678

2 KP123-445-677 677

In [119]: r_id = []
for i in ex['id'].str.split('-'):
r_id.append(i[-1])
print(r_id)

['678', '677']

In [120]: ex

Out[120]: id number

0 KP123-445-678 678

2 KP123-445-677 677
In [121]: ex['r_id'] = r_id

C:\Users\hakim\AppData\Local\Temp/ipykernel_9364/1805707212.py:1: SettingWithCopyWar
ning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/u


ser_guide/indexing.html#returning-a-view-versus-a-copy (https://pandas.pydata.org/pa
ndas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy)
ex['r_id'] = r_id

In [122]: ex

Out[122]: id number r_id

0 KP123-445-678 678 678

2 KP123-445-677 677 677

In [ ]: ​
In [1]: import numpy as np

In [93]: '''
rand(d0, d1, ..., dn)

Random values in a given shape.
'''
np.random.rand(5)

Out[93]: array([0.02797046, 0.27329249, 0.96250308, 0.51102897, 0.91144933])

In [3]: np.random.rand(5,3)

Out[3]: array([[0.75671313, 0.47523686, 0.07657354],


[0.96988545, 0.65884326, 0.07040573],
[0.47972916, 0.08948053, 0.21278647],
[0.06511173, 0.12869076, 0.27115767],
[0.58835437, 0.64445866, 0.68619386]])

In [4]: np.random.rand(3,2,2)

Out[4]: array([[[0.73543576, 0.20194153],


[0.16806944, 0.6655366 ]],

[[0.38388973, 0.79601924],
[0.46872426, 0.35585511]],

[[0.30234907, 0.27425016],
[0.94709762, 0.82155165]]])

In [41]: """
randint(low, high=None, size=None, dtype=int)

Return random integers from `low` (inclusive) to `high` (exclusive).
"""
np.random.randint(4,10,10)

Out[41]: array([5, 7, 4, 8, 9, 7, 8, 5, 6, 9])

In [42]: np.random.randint(4,10,(3,4))

Out[42]: array([[4, 4, 9, 8],


[6, 7, 4, 9],
[6, 6, 4, 9]])

In [43]: """
randn(d0, d1, ..., dn)

Return a sample (or samples) from the "standard normal" distribution.
-1 to +1
-3 to +3
"""
np.random.randn(12)

Out[43]: array([-0.67570659, 0.68119675, 0.11768435, -0.43513966, 0.11973263,


-0.67443269, 0.20239923, -0.20937164, 0.11231898, -0.42571108,
1.2990018 , 0.08392904])
In [74]: """
random(size=None)

Return random floats in the half-open interval [0.0, 1.0).
"""
np.random.random(10)

Out[74]: array([0.60576036, 0.34439086, 0.08917871, 0.11313322, 0.4655056 ,


0.05518852, 0.57738556, 0.32805669, 0.24725062, 0.69677092])

In [103]: a = [12,10,34,56,70,99]
np.random.choice(a,size=2)

Out[103]: array([70, 10])

In [108]: np.random.choice(a,size=(2,2))

Out[108]: array([[10, 12],


[56, 34]])

In [ ]: ​
In [1]: import numpy as np

In [3]: a = np.arange(24).reshape(2,12)
a

Out[3]: array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],


[12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]])

split()
In [4]: """
signature: np.split(ary, indices_or_sections, axis=0)
Docstring:
Split an array into multiple sub-arrays as views into `ary`.
"""
np.split(a,2)
# default axis = 0 means work on rows

Out[4]: [array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]]),


array([[12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]])]

In [7]: # axis=1 work on columns


np.split(a,2,axis=1)

Out[7]: [array([[ 0, 1, 2, 3, 4, 5],


[12, 13, 14, 15, 16, 17]]),
array([[ 6, 7, 8, 9, 10, 11],
[18, 19, 20, 21, 22, 23]])]

In [11]: np.split(a,4,axis=1)

Out[11]: [array([[ 0, 1, 2],


[12, 13, 14]]),
array([[ 3, 4, 5],
[15, 16, 17]]),
array([[ 6, 7, 8],
[18, 19, 20]]),
array([[ 9, 10, 11],
[21, 22, 23]])]

In [12]: # hsplit(): horizontal splitting


a

Out[12]: array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],


[12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]])

In [14]: #Split an array into multiple sub-arrays horizontally (column-wise).


np.hsplit(a,2)

Out[14]: [array([[ 0, 1, 2, 3, 4, 5],


[12, 13, 14, 15, 16, 17]]),
array([[ 6, 7, 8, 9, 10, 11],
[18, 19, 20, 21, 22, 23]])]
In [19]: # vsplit
np.vsplit(a,2)

Out[19]: [array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]]),


array([[12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]])]

Delete array
In [20]: a

Out[20]: array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],


[12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]])

In [21]: np.delete(a,-1)

Out[21]: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,


17, 18, 19, 20, 21, 22])

In [22]: # last row delete


np.delete(a,-1,axis=0)

Out[22]: array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]])

In [23]: # delete last column


np.delete(a,-1,axis=1)

Out[23]: array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],


[12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]])

In [24]: a

Out[24]: array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],


[12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]])

suppose i want to delete complete array

In [25]: del a

In [26]: a

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_6080/2167009006.py in <module>
----> 1 a

NameError: name 'a' is not defined

In [27]: # can we delete a row /column using del


b = np.random.random((4,4))
b

Out[27]: array([[0.09037876, 0.38006424, 0.84639761, 0.55521722],


[0.22892133, 0.06717815, 0.4736258 , 0.49635734],
[0.34956082, 0.73614149, 0.94007037, 0.03976513],
[0.29053554, 0.03616846, 0.20439108, 0.85807609]])
In [28]: b[:2]

Out[28]: array([[0.09037876, 0.38006424, 0.84639761, 0.55521722],


[0.22892133, 0.06717815, 0.4736258 , 0.49635734]])

In [29]: # lets delete 2 rows


del b[:2]
# del is used for to delete complete array/object nt element of array

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_6080/643977024.py in <module>
1 # lets delete 2 rows
----> 2 del b[:2]

ValueError: cannot delete array elements

#Q. np.delete and del what is difference????


sort()
In [30]: c = np.array([[12,9,45,89],[0,2,67,4],[11,80,37,21]])
c

Out[30]: array([[12, 9, 45, 89],


[ 0, 2, 67, 4],
[11, 80, 37, 21]])

In [31]: np.sort(c) #sorted rowwise

Out[31]: array([[ 9, 12, 45, 89],


[ 0, 2, 4, 67],
[11, 21, 37, 80]])

In [33]: # sort columnwise


np.sort(c,axis=0)

Out[33]: array([[ 0, 2, 37, 4],


[11, 9, 45, 21],
[12, 80, 67, 89]])

copy()
In [34]: c

Out[34]: array([[12, 9, 45, 89],


[ 0, 2, 67, 4],
[11, 80, 37, 21]])

In [36]: x = np.copy(c)
x

Out[36]: array([[12, 9, 45, 89],


[ 0, 2, 67, 4],
[11, 80, 37, 21]])
In [39]: id(c),id(x) # shallow copy

Out[39]: (2848781103344, 2848782912464)

In [40]: y = c #deep copy

In [41]: id(y),id(c)

Out[41]: (2848781103344, 2848781103344)

In [46]: c

Out[46]: array([[12, 9, 45, 89],


[ 0, 2, 67, 4],
[11, 80, 37, 21]])

In [47]: c.reshape(12)#order='C'

Out[47]: array([12, 9, 45, 89, 0, 2, 67, 4, 11, 80, 37, 21])

In [48]: c.reshape(12,order='F')

Out[48]: array([12, 0, 11, 9, 2, 80, 45, 67, 37, 89, 4, 21])

argmax,argmin

In [49]: c

Out[49]: array([[12, 9, 45, 89],


[ 0, 2, 67, 4],
[11, 80, 37, 21]])

In [51]: c.ravel()

Out[51]: array([12, 9, 45, 89, 0, 2, 67, 4, 11, 80, 37, 21])

In [50]: #Returns the indices of the maximum values along an axis.


np.argmax(c)

Out[50]: 3

In [52]: #but i want rowwise and columnwise max_index


np.argmax(c,axis=0)

Out[52]: array([0, 2, 1, 0], dtype=int64)

In [53]: np.argmax(c,axis=1)

Out[53]: array([3, 2, 1], dtype=int64)

In [54]: # create an empty array


np.empty(4)

Out[54]: array([2.22520967e-307, 1.61323372e-307, 4.67296746e-307, 1.69121096e-306])


In [55]: np.empty((4,4))

Out[55]: array([[0.09037876, 0.38006424, 0.84639761, 0.55521722],


[0.22892133, 0.06717815, 0.4736258 , 0.49635734],
[0.34956082, 0.73614149, 0.94007037, 0.03976513],
[0.29053554, 0.03616846, 0.20439108, 0.85807609]])

In [56]: # i have c array, and


# want to create a new EMPTY array with same dimension as that of c
np.empty_like(c)

Out[56]: array([[12, 0, 11, 9],


[ 2, 80, 45, 67],
[37, 89, 4, 21]])

In [58]: b

Out[58]: array([[0.09037876, 0.38006424, 0.84639761, 0.55521722],


[0.22892133, 0.06717815, 0.4736258 , 0.49635734],
[0.34956082, 0.73614149, 0.94007037, 0.03976513],
[0.29053554, 0.03616846, 0.20439108, 0.85807609]])

In [59]: np.empty_like(b)

Out[59]: array([[0.09037876, 0.38006424, 0.84639761, 0.55521722],


[0.22892133, 0.06717815, 0.4736258 , 0.49635734],
[0.34956082, 0.73614149, 0.94007037, 0.03976513],
[0.29053554, 0.03616846, 0.20439108, 0.85807609]])

In [60]: np.empty_like(np.empty((3,4)))

Out[60]: array([[1.40745969e-311, 2.81617418e-322, 0.00000000e+000,


0.00000000e+000],
[1.11260619e-306, 2.92966904e-033, 5.20651174e-090,
5.64053562e-062],
[9.98705260e-048, 1.54574045e+185, 6.48224660e+170,
4.93432906e+257]])

cumsum/cumprod

In [61]: c

Out[61]: array([[12, 9, 45, 89],


[ 0, 2, 67, 4],
[11, 80, 37, 21]])

In [62]: #Return the cumulative sum of the elements along a given axis.

np.cumsum(c)

Out[62]: array([ 12, 21, 66, 155, 155, 157, 224, 228, 239, 319, 356, 377],
dtype=int32)

In [63]: np.cumsum(c,axis=0)

Out[63]: array([[ 12, 9, 45, 89],


[ 12, 11, 112, 93],
[ 23, 91, 149, 114]], dtype=int32)
In [ ]: #cumprod() #cummulative product

In [64]: a = [[1, 0],


[0, 1]]

b = [[4, 1],
[2, 2]]
np.dot(a, b)

Out[64]: array([[4, 1],


[2, 2]])

In [65]: np.multiply(a,b)

Out[65]: array([[4, 0],


[0, 2]])

In [1]: np.add()
np.subtract()
np.divide()

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Input In [1], in <cell line: 1>()
----> 1 np.add()
2 np.subtract()
3 np.divide()

NameError: name 'np' is not defined

In [ ]: ​

You might also like