1.
Numpy Basics
([Link],[Link],[Link],[Link],np.
ones,[Link],[Link])
Np. ARRAY()
import numpy as np
data = [Link]([[1.5, -0.1, 3], [0, -3, 6.5]])
print(data)
OUT PUT
[[ 1.5 -0.1 3. ]
[ 0. -3. 6.5]]
import numpy as np
data = [Link]([[1.5, -0.1, 3], [0, -3, 6.5]])
print(data*10)
OUT PUT
[[ 15. -1. 30.]
[ 0. -30. 65.]]
import numpy as np
data = [Link]([[1.5, -0.1, 3], [0, -3, 6.5]])
print(data+data)
OUT PUT
[[ 3. -0.2 6. ]
[ 0. -6. 13. ]]
import numpy as np
data2 = [[1, 2, 3, 4], [5, 6, 7, 8]]
arr2 = [Link](data2)
print(arr2)
OUT PUT
[[1 2 3 4]
[5 6 7 8]]
import numpy as np
data2 = [[1, 2, 3, 4], [5, 6, 7, 8]]
arr2 = [Link](data2)
arr=[Link]
print(arr)
OUT PUT
[Link]
Using [Link]()
NumPy has its own version of the built-in range(). It’s called [Link](), and
unlike range(), it’s not restricted to just integers. You can use [Link]() in a
similar way to range(), using start, stop, and step as the input parameters:
[Link]([start, ]stop, [step, ]dtype=None, *, like=None)
Return evenly spaced values within a given interval.
arange can be called with a varying number of positional
arguments:
arange(stop): Values are generated within the half-open
interval [0, stop) (in other words, the interval
including start but excluding stop).
arange(start, stop): Values are generated within the half-
open interval [start, stop).
arange(start, stop, step) Values are generated within the
half-open interval [start, stop), with spacing between
values given by step.
import numpy as np
a=list(range(2, 30, 2))
print(a)
output
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]
import numpy as np
a=[Link](2, 30, 2)
print(a)
output
[ 2 4 6 8 10 12 14 16 18 20 22 24 26 28]
import numpy as np
a=[Link](2.34, 31.97, 2)
print(a)
Output
[ 2.34 4.34 6.34 8.34 10.34 12.34 14.34 16.34 18.34 20.34 22.34 24.34
26.34 28.34 30.34]
Here’s a good rule of thumb for deciding which of the two functions to use:
Use [Link]() when the exact values for the start and end points
of your range are the important attributes in your application.
Use [Link]() when the step size between values is more
important.
You’ll use [Link]() again in this tutorial. To learn more about it, check
out NumPy arange(): How to Use [Link]().
[Link]
Using [Link]()
[Link]() has two required parameters, start and stop, which you can
use to set the beginning and end of the range:
Using [Link]() with the start, stop, and num parameters is the most
common way of using the function, and for many applications you won’t need to
look beyond this approach. However, you can customize your output further.
The start, stop, and num Parameters
Although start and stop are the only required parameters, you’ll usually also
want to use a third parameter, num. The parameters start and stop are the
beginning and end of the range you wish to create, and num is an integer that
determines how many elements the output array will have.
import numpy as np
a=[Link](1, 10, num=10)
print(a)
output
[ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.]
import numpy as np
a=[Link](-10, 10, 25)
print(a)
output
[-10. -9.16666667 -8.33333333 -7.5 -6.66666667
-5.83333333 -5. -4.16666667 -3.33333333 -2.5
-1.66666667 -0.83333333 0. 0.83333333 1.66666667
2.5 3.33333333 4.16666667 5. 5.83333333
6.66666667 7.5 8.33333333 9.16666667 10. ]
import numpy as np
step = 20 / 24
a=[-10 + step*interval for interval in range(25)]
print(a)
output
[-10.0, -9.166666666666666, -8.333333333333334, -7.5, -6.666666666666666, -
5.833333333333333, -5.0, -4.166666666666666, -3.333333333333333, -2.5, -1.666666666666666, -
0.8333333333333321, 0.0, 0.8333333333333339, 1.6666666666666679, 2.5, 3.333333333333334,
4.166666666666668, 5.0, 5.833333333333334, 6.666666666666668, 7.5, 8.333333333333336,
9.166666666666668, 10.0]
import numpy as np
a=[Link](-5, 5, 100)
print(a)
output
[-5. -4.8989899 -4.7979798 -4.6969697 -4.5959596 -4.49494949
-4.39393939 -4.29292929 -4.19191919 -4.09090909 -3.98989899 -3.88888889
-3.78787879 -3.68686869 -3.58585859 -3.48484848 -3.38383838 -3.28282828
-3.18181818 -3.08080808 -2.97979798 -2.87878788 -2.77777778 -2.67676768
-2.57575758 -2.47474747 -2.37373737 -2.27272727 -2.17171717 -2.07070707
-1.96969697 -1.86868687 -1.76767677 -1.66666667 -1.56565657 -1.46464646
-1.36363636 -1.26262626 -1.16161616 -1.06060606 -0.95959596 -0.85858586
-0.75757576 -0.65656566 -0.55555556 -0.45454545 -0.35353535 -0.25252525
-0.15151515 -0.05050505 0.05050505 0.15151515 0.25252525 0.35353535
0.45454545 0.55555556 0.65656566 0.75757576 0.85858586 0.95959596
1.06060606 1.16161616 1.26262626 1.36363636 1.46464646 1.56565657
1.66666667 1.76767677 1.86868687 1.96969697 2.07070707 2.17171717
2.27272727 2.37373737 2.47474747 2.57575758 2.67676768 2.77777778
2.87878788 2.97979798 3.08080808 3.18181818 3.28282828 3.38383838
3.48484848 3.58585859 3.68686869 3.78787879 3.88888889 3.98989899
4.09090909 4.19191919 4.29292929 4.39393939 4.49494949 4.5959596
4.6969697 4.7979798 4.8989899 5. ]
Even though all elements are whole numbers, they’re still displayed with a trailing period to
show that they’re floats. You confirm that by looking at the value of [Link].
You can use the optional dtype input parameter to change the data type of the elements in
the output array:
>>>
import numpy as np
numbers = [Link](-10, 10, 11, dtype=int)
print(numbers)
output
[-10 -8 -6 -4 -2 0 2 4 6 8 10]
import numpy as np
numbers = [Link](-10, 10, 11, dtype=int)
print(numbers)
numbers, step = [Link](-5, 5, 20, retstep=True)
print(numbers)
output
[-10 -8 -6 -4 -2 0 2 4 6 8 10]
[-5. -4.47368421 -3.94736842 -3.42105263 -2.89473684 -2.36842105
-1.84210526 -1.31578947 -0.78947368 -0.26315789 0.26315789 0.78947368
1.31578947 1.84210526 2.36842105 2.89473684 3.42105263 3.94736842
4.47368421 5.
import numpy as np
output = [Link](start=[2, 5, 9],
stop=[100, 130, 160],
num=10, axis=1)
print(output)
[[ 2. 12.88888889 23.77777778 34.66666667 45.55555556
56.44444444 67.33333333 78.22222222 89.11111111 100. ]
[ 5. 18.88888889 32.77777778 46.66666667 60.55555556
Default
Parameter Description value
start and sto These required parameters define the beginning and end of the range. Often -
p these will be scalar values, either int or float, but can be any array-like
object.
num This parameter defines the number of points in the array, often referred to as 50
sampling or resolution.
endpoint If this parameter is set to False, then the function treats the interval as a half- True
open interval and excludes the endpoint from the output array.
retstep If this parameter is set to True, then the function returns the array and False
a float with the step size between each element of the linear space. Otherwise,
only the array is returned.
dtype This parameter can be used to set the data type of the elements in the output -
array.
axis This parameter is used only with nonscalar start and stop values. It -
determines the axis along which the results are stored.
74.44444444 88.33333333 102.22222222 116.11111111 130. ]
[ 9. 25.77777778 42.55555556 59.33333333 76.11111111
92.88888889 109.66666667 126.44444444 143.22222222 160. ]]
The key points to remember about the input parameters are listed below:
The outputs returned from calling the function are listed below:
An array of type ndarray containing the vector space
The step size as a float, if retstep is set to True
You can use this section as a reference when you start experimenting
with [Link]() and the different ways you can customize its output.
ZEROS()
[Link]([start, ]stop, [step, ]dtype=None, *, like=None)
Return evenly spaced values within a given interval.
arange can be called with a varying number of positional
arguments:
arange(stop): Values are generated within the half-open
interval [0, stop) (in other words, the interval
including start but excluding stop).
arange(start, stop): Values are generated within the half-
open interval [start, stop).
arange(start, stop, step) Values are generated within the
half-open interval [start, stop), with spacing between
values given by step.
import numpy as np
l=[Link](10)
print(l)
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
import numpy as np
a=[Link]((5,), dtype=int)
print(a)
output
[0 0 0 0 0]
import numpy as np
a=[Link]((2, 1))
print(a)
output
[[0.]
[0.]]
import numpy as np
a=[Link]((2,), dtype=[('x', 'i4'), ('y', 'i4')])
print(a)
[(0, 0) (0, 0)]
dtype=[('x', '<i4'), ('y', '<i4')])
[Link]
numpy.ones_like(a, dtype=None, order='K', subok=True, shape=None)[source]
Return an array of ones with the same shape and type as a given
array.
Parameters:
aarray_like
The shape and data-type of a define these same attributes of the
returned array.
dtypedata-type, optional
Overrides the data type of the result.
order{‘C’, ‘F’, ‘A’, or ‘K’}, optional
Overrides the memory layout of the result. ‘C’ means C-order, ‘F’
means F-order, ‘A’ means ‘F’ if a is Fortran contiguous, ‘C’
otherwise. ‘K’ means match the layout of a as closely as possible.
New in version 1.6.0.
subokbool, optional.
If True, then the newly created array will use the sub-class type of a,
otherwise it will be a base-class array. Defaults to True.
shapeint or sequence of ints, optional.
Overrides the shape of the result. If order=’K’ and the number of
dimensions is unchanged, will try to keep order, otherwise,
order=’C’ is implied.
New in version 1.17.0.
Returns:
outndarray
Array of ones with the same shape and type as a.
See also
empty_like
Return an empty array with shape and type of input.
zeros_like
Return an array of zeros with shape and type of input.
full_like
Return a new array with shape of input filled with value.
ones
Return a new array setting values to one.
import numpy as np
x = [Link](6)
x = [Link]((2, 3))
print(x)
output
[[0 1 2]
[3 4 5]]
import numpy as np
x = [Link](6)
x = [Link]((2, 3))
p=np.ones_like(x)
print(p)
output
[[1 1 1]
[1 1 1]]
import numpy as np
x = [Link](6)
x = [Link]((2, 3))
p=np.ones_like(x)
print(p)
y = [Link](3, dtype=float)
print(y)
[[1 1 1]
[1 1 1]]
[0. 1. 2.]
numpy.empty_like
numpy.empty_like(prototype, dtype=None, order='K', subok=True, sh
ape=None)
Return a new array with the same shape and type as a given array.
Parameters:
prototypearray_like
The shape and data-type of prototype define these same attributes
of the returned array.
dtypedata-type, optional
Overrides the data type of the result.
New in version 1.6.0.
order{‘C’, ‘F’, ‘A’, or ‘K’}, optional
Overrides the memory layout of the result. ‘C’ means C-order, ‘F’
means F-order, ‘A’ means ‘F’ if prototype is Fortran contiguous, ‘C’
otherwise. ‘K’ means match the layout of prototype as closely as
possible.
New in version 1.6.0.
subokbool, optional.
If True, then the newly created array will use the sub-class type
of prototype, otherwise it will be a base-class array. Defaults to
True.
shapeint or sequence of ints, optional.
Overrides the shape of the result. If order=’K’ and the number of
dimensions is unchanged, will try to keep order, otherwise,
order=’C’ is implied.
New in version 1.17.0.
Returns:
outndarray
Array of uninitialized (arbitrary) data with the same shape and type
as prototype.
See also
ones_like
Return an array of ones with shape and type of input.
zeros_like
Return an array of zeros with shape and type of input.
full_like
Return a new array with shape of input filled with value.
empty
Return a new uninitialized array.
import numpy as np
a = ([1,2,3], [4,5,6])
print(np.empty_like(a))
[[1520878264 458 5]
[ 0 1520913504 458]]
import numpy as np
x=[Link]([2, 2])
print(x)
[[5.e-324 4.e-323]
[4.e-323 4.e-323]]
import numpy as np
x=[Link]([2, 2], dtype=int)
print(x)
[[ -968675049 -1668507101]
[-1025012281 -875328881]]
import numpy as np
a = [Link]([[1., 2., 3.],[4.,5.,6.]])
print(np.empty_like(a))
[[0. 0. 0.]
[0. 0. 0.]]
import numpy as np
a = [Link]([[1., 2., 3.],[4.,5.,6.]])
print(np.empty_like(a))
[[-6.95194991e-310 6.43259850e-235 1.21469340e-311]
[ 1.21469340e-311 1.97626258e-323 5.43472210e-323]]
[Link]
[Link](size=None)
Return random floats in the half-open interval [0.0, 1.0). Alias
for random_sample to ease forward-porting to the new random API.
[Link].random_integers
random.random_integers(low, high=None, size=None)
Random integers of type np.int_ between low and high, inclusive.
Return random integers of type np.int_ from the “discrete uniform”
distribution in the closed interval [low, high]. If high is None (the
default), then results are from [1, low]. The np.int_ type translates to
the C long integer type and its precision is platform dependent.
Parameters:
lowint
Lowest (signed) integer to be drawn from the distribution
(unless high=None, in which case this parameter is the highest such
integer).
highint, optional
If provided, the largest (signed) integer to be drawn from the
distribution (see above for behavior if high=None).
sizeint or tuple of ints, optional
Output shape. If the given shape is, e.g., (m, n, k),
then m * n * k samples are drawn. Default is None, in which case a
single value is returned.
import numpy as np
a=[Link].random_integers(5, size=(3,2))
print(a)
output
[[4 5]
[4 2]
[4 4]]
import numpy as np
d1 = [Link].random_integers(1, 6, 1000)
d2 = [Link].random_integers(1, 6, 1000)
dsums = d1 + d2
print(dsums)
[ 8 7 3 4 4 5 7 2 7 5 7 4 2 8 7 7 5 8 11 10 10 9 8 5
9 6 7 6 4 5 8 7 8 6 6 2 6 5 8 2 8 7 9 8 5 9 12 8
10 10 5 7 7 7 9 5 7 12 6 5 11 7 2 10 7 4 3 10 7 7 10 7
10 9 9 8 9 9 4 4 5 4 9 5 3 8 11 7 6 4 4 7 6 4 10 7
8 3 11 6]
import [Link] as plt
import numpy as np
d1 = [Link].random_integers(1, 6, 1000)
d2 = [Link].random_integers(1, 6, 1000)
dsums = d1 + d2
count, bins, ignored = [Link](dsums, 11, density=True)
print([Link]())
[Link]
[Link](size=None)
Return random floats in the half-open interval [0.0, 1.0). Alias
for random_sample to ease forward-porting to the new random API.
Numpy Random
In NumPy, we have a module called random which provides functions for
generating random numbers.
These functions can be useful for generating random inputs for testing
algorithms.
import numpy as np
rng = [Link].default_rng()
print([Link]())
0.43272968690198776
import numpy as np
random_number = [Link](0, 10)
print(random_number)
output: 9
integer_array = [Link](0, 10, 5)
print("1D Random Integer Array:\n",integer_array)
float_array = [Link](5)
print("\n1D Random Float Array:\n",float_array)
result = [Link](0, 10, (3,4))
print("\n2D Random Integer Array:\n",result)
1D Random Integer Array:
[7 9 3 6 0]
1D Random Float Array:
[0.05865581 0.17446034 0.59101576 0.39505289 0.25466584]
2D Random Integer Array:
[[3 7 1 0]
[3 2 4 8]
[3 3 1 1]]
Table 4.2: NumPy data types
Type Type code Description
Signed and unsigned 8-bit (1
int8, uint8 i1, u1 byte) integer types
int16, uint16 i2, u2 Signed and unsigned 16-bit
Table 4.2: NumPy data types
Type Type code Description
integer types
Signed and unsigned 32-bit
int32, uint32 i4, u4 integer types
Signed and unsigned 64-bit
int64, uint64 i8, u8 integer types
float16 f2 Half-precision floating point
Standard single-precision
float32 f4 or f floating point; compatible with
C float
Standard double-precision
floating point; compatible with
float64 f8 or d C double and
Python float object
Extended-precision floating
float128 f16 or g point
complex64, complex128, compl c8, c16, Complex numbers represented
by two 32, 64, or 128 floats,
ex256 c32 respectively
Boolean type
bool ? storing True and False values
Python object type; a value
object O can be any Python object
Fixed-length ASCII string type
(1 byte per character); for
string_ S example, to create a string
data type with length 10,
use 'S10'
unicode_ U Fixed-length Unicode type
(number of bytes platform
specific); same specification
semantics
Table 4.2: NumPy data types
Type Type code Description
as string_ (e.g., 'U10')