Sie sind auf Seite 1von 26

object : array_like

An array, any object exposing the array interface, an object whose __array__
method returns an array, or any (nested) sequence.
dtype : data-type, optional
The desired data-type for the array. If not given, then the type will be determined as
the minimum type required to hold the objects in the sequence. This argument can
only be used to ‘upcast’ the array. For downcasting, use the .astype(t) method.
copy : bool, optional
If true (default), then the object is copied. Otherwise, a copy will only be made if
__array__ returns a copy, if obj is a nested sequence, or if a copy is needed to
satisfy any of the other requirements (dtype, order, etc.).
order : There can be 3 possible values assigned to this point.It can be C(column order),
R(row order), or A(Any).
subok : bool, optional
If True, then sub-classes will be passed-through, otherwise the returned array will
be forced to be a base-class array (default).
ndmin : int, optional
Specifies the minimum number of dimensions that the resulting array should have.
Ones will be pre-pended to the shape as needed to meet this requirement.
NumPy Datatypes

The NumPy provides a higher range of numeric data types than that provided by the Python.
A list of numeric data types is given in the following table.

SN Data type Description


1 bool_ It represents the boolean value indicating true or false. It is stored as a
byte.
2 int_ It is the default type of integer. It is identical to long type in C that
contains 64 bit or 32-bit integer.
3 intc It is similar to the C integer (c int) as it represents 32 or 64-bit int.
4 intp It represents the integers which are used for indexing.
5 int8 It is the 8-bit integer identical to a byte. The range of the value is -128
to 127.
6 int16 It is the 2-byte (16-bit) integer. The range is -32768 to 32767.
7 int32 It is the 4-byte (32-bit) integer. The range is -2147483648 to
2147483647.
8 int64 It is the 8-byte (64-bit) integer. The range is -9223372036854775808
to 9223372036854775807.
9 uint8 It is the 1-byte (8-bit) unsigned integer.
10 uint16 It is the 2-byte (16-bit) unsigned integer.
11 uint32 It is the 4-byte (32-bit) unsigned integer.
12 uint64 It is the 8 bytes (64-bit) unsigned integer.
13 float_ It is identical to float64.

14 float16 It is the half-precision float. 5 bits are reserved for the exponent. 10
bits are reserved for mantissa, and 1 bit is reserved for the sign.

15 float32 It is a single precision float. 8 bits are reserved for the exponent, 23
bits are reserved for mantissa, and 1 bit is reserved for the sign.

16 float64 It is the double precision float. 11 bits are reserved for the exponent, 52
bits are reserved for mantissa, 1 bit is used for the sign.

17 complex_ It is identical to complex128.

18 complex64 It is used to represent the complex number where real and imaginary
part shares 32 bits each.
19 complex128 It is used to represent the complex number where real and imaginary
part shares 64 bits each.
(i)numpy.split(ary, indices_or_sections, axis=0):
Split an array into multiple sub-arrays.
Parameters:
ary : ndarray
Array to be divided into sub-arrays.
indices_or_sections : int or 1-D array
If indices_or_sections is an integer, N, the array will be
divided into N equal arrays along axis. If such a split is not
possible, an error is raised.
If indices_or_sections is a 1-D array of sorted integers, the
entries indicate where along axis the array is split. For
example, [2, 3] would, for axis=0, result in
ary[:2]
ary[2:3]
ary[3:]

If an index exceeds the dimension of the array along axis, an


empty sub-array is returned correspondingly.
axis : int, optional
The axis along which to split, default is 0.
Returns:
sub-arrays : list of ndarrays
A list of sub-arrays.
Examples
(a) x = np.arange(9.0)
np.split(x, 3)
[array([ 0., 1., 2.]), array([ 3., 4., 5.]), array([ 6., 7., 8.])]
(b)x = np.arange(8.0)
np.split(x, [3, 5, 6, 10])
[array([ 0., 1., 2.]),
array([ 3., 4.]),
array([ 5.]),
array([ 6., 7.]),
array([], dtype=float64)]

(ii)numpy.array_split(ary, indices_or_sections, axis=0)


Split an array into multiple sub-arrays.
The only difference between these functions is at array_split allows
indices_or_sections to be an integer that does not equally divide the axis. For an array
of length l that should be split into n sections, it returns l % n sub-arrays of size l//n + 1
and the rest of size l//n.
Examples
(a) x = np.arange(8.0)
np.array_split(x, 3)
[array([ 0., 1., 2.]), array([ 3., 4., 5.]), array([ 6., 7.])]
(b) x = np.arange(7.0)
np.array_split(x, 3) = [array([ 0., 1., 2.]), array([ 3., 4.]), array([ 5., 6.])]

(iii)numpy.hsplit(ary, indices_or_sections):
Split an array into multiple sub-arrays horizontally (column-wise).hsplit is equivalent
to split with axis=1, the array is always split along the second axis regardless of the
array dimension.
Examples
(a) x = np.arange(16.0).reshape(4, 4)
np.hsplit(x, 2) = [array([[ 0., 1.],[ 4., 5.], [ 8., 9.], [ 12., 13.]]),
array([[ 2., 3.], [ 6., 7.], [ 10., 11.], [ 14.,15.]])]
np.hsplit(x, np.array([3, 6]))(split array after 3rd and 6th columns)
= [array([[ 0., 1., 2.], [ 4., 5., 6.], [ 8., 9., 10.],
[ 12., 13., 14.]]),
array([[ 3.], [ 7.], [ 11.], [ 15.]]),
array([],shape=(4, 0), dtype=float64)]
With a higher dimensional array the split is still along the second axis.
(b) x = np.arange(8.0).reshape(2, 2, 2)
x = array([[[ 0., 1.], [ 2., 3.]], [[ 4., 5.], [ 6., 7.]]])
np.hsplit(x, 2) = [array([[[ 0., 1.]], [[ 4., 5.]]]),
array([[[ 2., 3.]], [[ 6., 7.]]])]
(iv) numpy.vsplit(ary, indices_or_sections)
Split an array into multiple sub-arrays vertically (row-wise).vsplit is equivalent to
split with axis=0 (default), the array is always split along the first axis regardless of
the array dimension.
Examples
(a) x = np.arange(16.0).reshape(4, 4)
x = array([[ 0., 1., 2., 3.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.],
[ 12., 13., 14., 15.]])
np.vsplit(x, 2) = [array([[ 0., 1., 2., 3.], [ 4., 5., 6., 7.]]),
array([[ 8., 9., 10., 11.], [ 12., 13., 14., 15.]])]
np.vsplit(x, np.array([3, 6])) (split array after 3rd and 6th rows)
= [array([[ 0., 1., 2., 3.], [ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]]),
array([[ 12., 13., 14., 15.]]),
array([], shape=(0, 4),dtype=float64)]
(b)With a higher dimensional array the split is still along the first axis.
x = np.arange(8.0).reshape(2, 2, 2)
x = array([[[ 0., 1.], [ 2., 3.]], [[ 4., 5.], [ 6., 7.]]])
np.vsplit(x, 2) = [array([[[ 0., 1.], [ 2., 3.]]]),
array([[[ 4., 5.], [ 6., 7.]]])]

(v) numpy.dsplit(ary, indices_or_sections)


Split array into multiple sub-arrays along the 3rd axis (depth).dsplit is equivalent to
split with axis=2, the array is always split along the third axis provided the array
dimension is greater than or equal to 3.

Examples
(a)x = np.arange(16.0).reshape(2, 2, 4)
x = array([[[ 0., 1., 2., 3.], [ 4., 5., 6., 7.]],
[[ 8., 9., 10., 11.], [ 12., 13., 14., 15.]]])
np.dsplit(x, 2) = [array([[[ 0., 1.], [ 4., 5.]],
[[ 8., 9.], [ 12., 13.]]]),
array([[[ 2., 3.], [ 6., 7.]],
[[ 10., 11.], [ 14., 15.]]])]
np.dsplit(x, np.array([3, 6])) = [array([[[ 0., 1., 2.],[ 4., 5., 6.]],
[[ 8., 9., 10.],[ 12., 13., 14.]]]),
array([[[ 3.],[ 7.]],[[ 11.],[ 15.]]]),
array([], dtype=float64)]
Numpy Array Creation
The ndarray object can be constructed by using the following routines.
(i)Numpy.empty
As the name specifies, The empty routine is used to create an uninitialized array of specified
shape and data type.
The syntax is given below.
numpy.empty(shape, dtype = float, order = 'C')
It accepts the following parameters.
o Shape: The desired shape of the specified array.
o dtype: The data type of the array items. The default is the float.
o Order: The default order is the c-style row-major order. It can be set to F for
FORTRAN-style column-major order.
Example
import numpy as np
arr = np.empty((3,2), dtype = int)
print(arr)
Output:
[[ 140482883954664 36917984], [ 140482883954648 140482883954648]
[6497921830368665435 172026472699604272]]
(ii)NumPy.Zeros
This routine is used to create the numpy array with the specified shape where each numpy
array item is initialized to 0.
The syntax is given below.
numpy.zeros(shape, dtype = float, order = 'C')
It accepts the following parameters.
o Shape: The desired shape of the specified array.
o dtype: The data type of the array items. The default is the float.
o Order: The default order is the c-style row-major order. It can be set to F for
FORTRAN-style column-major order.
Example
import numpy as np
arr = np.zeros((3,2), dtype = int)
print(arr)
Output:
[[0 0], [0 0], [0 0]]
(iii)NumPy.ones
This routine is used to create the numpy array with the specified shape where each numpy
array item is initialized to 1.
The syntax to use this module is given below.
numpy.ones(shape, dtype = none, order = 'C')
It accepts the following parameters.
o Shape: The desired shape of the specified array.
o dtype: The data type of the array items.
o Order: The default order is the c-style row-major order. It can be set to F for
FORTRAN-style column-major order.
Example
import numpy as np
arr = np.ones((3,2), dtype = int)
print(arr)
Output:
[[1 1], [1 1], [1 1]]
Numpy array from existing data

NumPy provides us the way to create an array by using the existing data.
(i)numpy.asarray

This routine is used to create an array by using the existing data in the form of lists, or tuples.
This routine is useful in the scenario where we need to convert a python sequence into the
numpy array object.

The syntax to use the asarray() routine is given below.


numpy.asarray(sequence, dtype = None, order = None)

It accepts the following parameters.


1. sequence: It is the python sequence which is to be converted into the python array.
2. dtype: It is the data type of each item of the array.
3. order: It can be set to C or F. The default is C.
Example: creating numpy array using the list
import numpy as np
l=[1,2,3,4,5,6,7]
a = np.asarray(l);
print(type(a))
print(a)
Output:
<class 'numpy.ndarray'>
[1 2 3 4 5 6 7]
Example: creating a numpy array using Tuple
import numpy as np
l=(1,2,3,4,5,6,7)
a = np.asarray(l);
print(type(a))
print(a)
Output:
<class 'numpy.ndarray'>
[1 2 3 4 5 6 7]
Example: creating a numpy array using more than one list
import numpy as np
l=[[1,2,3,4,5,6,7],[8,9]]
a = np.asarray(l);
print(type(a))
print(a)
Output:
<class 'numpy.ndarray'>
[list([1, 2, 3, 4, 5, 6, 7]) list([8, 9])]

(ii)numpy.frombuffer
This function is used to create an array by using the specified buffer. The syntax to use this
buffer is given below.
numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0)

It accepts the following parameters.


o buffer: It represents an object that exposes a buffer interface.
o dtype: It represents the data type of the returned data type array. The default value is
0.
o count: It represents the length of the returned ndarray. The default value is -1.
o offset: It represents the starting position to read from. The default value is 0.
Example
import numpy as np
l = b'hello world'
print(type(l))
a = np.frombuffer(l, dtype = "S1")
print(a)
print(type(a))
Output:
<class 'bytes'>
[b'h' b'e' b'l' b'l' b'o' b' ' b'w' b'o' b'r' b'l' b'd']
<class 'numpy.ndarray'>

(iii)numpy.fromiter
This routine is used to create a ndarray by using an iterable object. It returns a one-
dimensional ndarray object.The syntax is given below.
numpy.fromiter(iterable, dtype, count = - 1)

It accepts the following parameters.


1. Iterable: It represents an iterable object.
2. dtype: It represents the data type of the resultant array items.
3. count: It represents the number of items to read from the buffer in the array.
Example
import numpy as np
list = [0,2,4,6]
it = iter(list)
x = np.fromiter(it, dtype = float)
print(x)
print(type(x))
Output:
[0. 2. 4. 6.]
<class 'numpy.ndarray'>

Numpy Arrays Within The Numerical Range:


This section of the tutorial illustrates how the numpy arrays can be created using some given
specified range.
(i)Numpy.arrange:
It creates an array by using the evenly spaced values over the given interval. The syntax to
use the function is given below.
numpy.arrange(start, stop, step, dtype)
It accepts the following parameters.
start: The starting of an interval. The default is 0.
stop: represents the value at which the interval ends excluding this value.
step: The number by which the interval values change.
dtype: the data type of the numpy array items.
Example
import numpy as np
arr = np.arange(0,10,2,float)
print(arr)
Output:
[0. 2. 4. 6. 8.]
Example
import numpy as np
arr = np.arange(10,100,5,int)
print("The array over the given range is ",arr)
Output:
The array over the given range is [10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95]
(ii)NumPy.linspace:
It is similar to the arrange function. However, it doesn?t allow us to specify the step size in
the syntax.
Instead of that, it only returns evenly separated values over a specified period. The system
implicitly calculates the step size.
The syntax is given below.
numpy.linspace(start, stop, num, endpoint, retstep, dtype)
It accepts the following parameters.
start: It represents the starting value of the interval.
stop: It represents the stopping value of the interval.
num: The amount of evenly spaced samples over the interval to be generated. The default is
50.
endpoint: Its true value indicates that the stopping value is included in the interval.
rettstep: This has to be a boolean value. Represents the steps and samples between the
consecutive numbers.
dtype: It represents the data type of the array items.
Example
import numpy as np
arr = np.linspace(10, 20, 5)
print("The array over the given range is ",arr)
Output:
The array over the given range is [10. 12.5 15. 17.5 20.]
Example
import numpy as np
arr = np.linspace(10, 20, 5, endpoint = False)
print("The array over the given range is ",arr)
Output:
The array over the given range is [10. 12. 14. 16. 18.]
(iii)numpy.logspace:
It creates an array by using the numbers that are evenly separated on a log scale.
The syntax is given below.
numpy.logspace(start, stop, num, endpoint, base, dtype)
It accepts the following parameters.
start: It represents the starting value of the interval in the base.
stop: It represents the stopping value of the interval in the base.
num: The number of values between the range.
endpoint: It is a boolean type value. It makes the value represented by stop as the last value
of the interval.
base: It represents the base of the log space.
dtype: It represents the data type of the array items.
Example
import numpy as np
arr = np.logspace(10, 20, num = 5, endpoint = True)
print("The array over the given range is ",arr)
Output:
The array over the given range is [1.00000000e+10 3.16227766e+12 1.00000000e+15
3.16227766e+17 1.00000000e+20]
Example
import numpy as np
arr = np.logspace(10, 20, num = 5,base = 2, endpoint = True)
print("The array over the given range is ",arr)
Output:
The array over the given range is [1.02400000e+03 5.79261875e+03 .27680000e+04
1.85363800e+05 1.04857600e+06]

NumPy Broadcasting
In Mathematical operations, we may need to consider the arrays of different shapes. NumPy
can perform such operations where the array of different shapes are involved.
For example, if we consider the matrix multiplication operation, if the shape of the two matrices
is the same then this operation will be easily performed. However, we may also need to operate
if the shape is not similar.
Consider the following example to multiply two arrays.
Example
import numpy as np
a = np.array([1,2,3,4,5,6,7])
b = np.array([2,4,6,8,10,12,14])
c = a*b;
print(c)
Output:
[ 2 8 18 32 50 72 98]
However, in the above example, if we consider arrays of different shapes, we will get the errors
as shown below.
Example
import numpy as np
a = np.array([1,2,3,4,5,6,7])
b = np.array([2,4,6,8,10,12,14,19])
c = a*b;
print(c)
Output:
ValueError: operands could not be broadcast together with shapes (7,) (8,)
In the above example, we can see that the shapes of the two arrays are not similar and therefore
they cannot be multiplied together. NumPy can perform such operation by using the concept
of broadcasting.
In broadcasting, the smaller array is broadcast to the larger array to make their shapes
compatible with each other.
Broadcasting Rules
Broadcasting is possible if the following cases are satisfied.
1. The smaller dimension array can be appended with '1' in its shape.
2. Size of each output dimension is the maximum of the input sizes in the dimension.
3. An input can be used in the calculation if its size in a particular dimension matches
the output size or its value is exactly 1.
4. If the input size is 1, then the first data entry is used for the calculation along the
dimension.
Broadcasting can be applied to the arrays if the following rules are satisfied.
1. All the input arrays have the same shape.
2. Arrays have the same number of dimensions, and the length of each dimension is
either a common length or 1.
3. Array with the fewer dimension can be appended with '1' in its shape.
Let's see an example of broadcasting.
Example
import numpy as np
a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
b = np.array([2,4,6,8])
print("\nprinting array a..")
print(a)
print("\nprinting array b..")
print(b)
print("\nAdding arrays a and b ..")
c = a + b;
print(c)
Output:
printing array a..
[[ 1 2 3 4]
[ 2 4 5 6]
[10 20 39 3]]

printing array b..


[2 4 6 8]

Adding arrays a and b ..


[[ 3 6 9 12]
[ 4 8 11 14]
[12 24 45 11]]

NumPy Array Iteration


NumPy provides an iterator object, i.e., nditer which can be used to iterate over the given array using python
standard Iterator interface.
Consider the following example.
Example
import numpy as np
a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
print("Printing array:")
print(a);
print("Iterating over the array:")
for x in np.nditer(a):
print(x,end=' ')
Output:
Printing array:
[[ 1 2 3 4]
[ 2 4 5 6]
[10 20 39 3]]
Iterating over the array:
1 2 3 4 2 4 5 6 10 20 39 3
Order of the iteration doesn't follow any special ordering like row-major or column-order. However, it is
intended to match the memory layout of the array.
Let's iterate over the transpose of the array given in the above example.
Example
import numpy as np
a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
print("Printing the array:")
print(a)
print("Printing the transpose of the array:")
at = a.T
print(at)

#this will be same as previous


for x in np.nditer(at):
print(print("Iterating over the array:")
for x in np.nditer(a):
print(x,end=' ')
Output:
Printing the array:
[[ 1 2 3 4]
[ 2 4 5 6]
[10 20 39 3]]
Printing the transpose of the array:
[[ 1 2 10]
[ 2 4 20]
[ 3 5 39]
[ 4 6 3]]
1 2 3 4 2 4 5 6 10 20 39 3
Order of Iteration
As we know, there are two ways of storing values into the numpy arrays:
F-style order
C-style order
Let's see an example of how the numpy Iterator treats the specific orders (F or C).
Example
import numpy as np
a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
print("\nPrinting the array:\n")
print(a)
print("\nPrinting the transpose of the array:\n")
at = a.T
print(at)
print("\nIterating over the transposed array\n")
for x in np.nditer(at):
print(x, end= ' ')
print("\nSorting the transposed array in C-style:\n")
c = at.copy(order = 'C')
print(c)
print("\nIterating over the C-style array:\n")
for x in np.nditer(c):
print(x,end=' ')
d = at.copy(order = 'F')
print(d)
print("Iterating over the F-style array:\n")
for x in np.nditer(d):
print(x,end=' ')
Output:
Printing the array:
[[ 1 2 3 4]
[ 2 4 5 6]
[10 20 39 3]]
Printing the transpose of the array:
[[ 1 2 10]
[ 2 4 20]
[ 3 5 39]
[ 4 6 3]]
Iterating over the transposed array
1 2 3 4 2 4 5 6 10 20 39 3
Sorting the transposed array in C-style:
[[ 1 2 10]
[ 2 4 20]
[ 3 5 39]
[ 4 6 3]]

Iterating over the C-style array:


1 2 10 2 4 20 3 5 39 4 6 3 [[ 1 2 10]
[ 2 4 20]
[ 3 5 39]
[ 4 6 3]]

Iterating over the F-style array:


1 2 3 4 2 4 5 6 10 20 39 3
We can mention the order 'C' or 'F' while defining the Iterator object itself. Consider the following example.
Example
import numpy as np
a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
print("\nPrinting the array:\n")
print(a)
print("\nPrinting the transpose of the array:\n")
at = a.T
print(at)
print("\nIterating over the transposed array\n")
for x in np.nditer(at):
print(x, end= ' ')
print("\nSorting the transposed array in C-style:\n")
print("\nIterating over the C-style array:\n")
for x in np.nditer(at, order = 'C'):
print(x,end=' ')
Output:
Iterating over the transposed array
1 2 3 4 2 4 5 6 10 20 39 3
Sorting the transposed array in C-style:
Iterating over the C-style array:
1 2 10 2 4 20 3 5 39 4 6 3
Array Values Modification
We can not modify the array elements during the iteration since the op-flag associated with the Iterator object is
set to readonly.
However, we can set this flag to readwrite or write only to modify the array values. Consider the following
example.
Example
import numpy as np
a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
print("\nPrinting the original array:\n")
print(a)
print("\nIterating over the modified array\n")
for x in np.nditer(a, op_flags = ['readwrite']):
x[...] = 3 * x;
print(x,end = ' ')
Output:
Printing the original array:
[[ 1 2 3 4]
[ 2 4 5 6]
[10 20 39 3]]

Iterating over the modified array


3 6 9 12 6 12 15 18 30 60 117 9

NumPy Bitwise Operators


Numpy provides the following bitwise operators.

SN Operator Description

1 bitwise_and It is used to calculate the bitwise and operation between the corresponding array elements.

2 bitwise_or It is used to calculate the bitwise or operation between the corresponding array elements.

3 invert It is used to calculate the bitwise not the operation of the array elements.

4 left_shift It is used to shift the bits of the binary representation of the elements to the left.

5 right_shift It is used to shift the bits of the binary representation of the elements to the right.

bitwise_and Operation
The NumPy provides the bitwise_and() function which is used to calculate the bitwise_and operation of the two
operands.
The bitwise and operation is performed on the corresponding bits of the binary representation of the operands. If
both the corresponding bit in the operands is set to 1, then only the resultant bit in the AND result will be set to 1
otherwise it will be set to 0.
Example
import numpy as np
a = 10
b = 12
print("binary representation of a:",bin(a))
print("binary representation of b:",bin(b))
print("Bitwise-and of a and b: ",np.bitwise_and(a,b))
Output:
binary representation of a: 0b1010
binary representation of b: 0b1100
Bitwise-and of a and b: 8
AND Truth Table
The output of the AND result of the two bits is 1 if and only if both the bits are 1 otherwise it will be 0.

A B AND (A, B)

0 0 0

0 1 0

1 0 0

1 1 1
bitwise_or Operator
The NumPy provides the bitwise_or() function which is used to calculate the bitwise or operation of the two
operands.
The bitwise or operation is performed on the corresponding bits of the binary representation of the operands. If
one of the corresponding bit in the operands is set to 1 then the resultant bit in the OR result will be set to 1;
otherwise it will be set to 0.
Example
import numpy as np
a = 50
b = 90
print("binary representation of a:",bin(a))
print("binary representation of b:",bin(b))
print("Bitwise-or of a and b: ",np.bitwise_or(a,b))
Output:
binary representation of a: 0b110010
binary representation of b: 0b1011010
Bitwise-or of a and b: 122
Or truth table
The output of the OR result of the two bits is 1 if one of the bits are 1 otherwise it will be 0.

A B Or (A, B)

0 0 0

0 1 1

1 0 1

1 1 1

Invert operation
It is used to calculate the bitwise not the operation of the given operand. The 2's complement is returned if the
signed integer is passed in the function.
Consider the following example.
Example
import numpy as np
arr = np.array([20],dtype = np.uint8)
print("Binary representation:",np.binary_repr(20,8))
print(np.invert(arr))
print("Binary representation: ", np.binary_repr(235,8))
Output:
Binary representation: 00010100 [235]
Binary representation: 11101011
It shifts the bits in the binary representation of the operand to the left by the specified position. An equal number
of 0s are appended from the right. Consider the following example.
Example
import numpy as np
print("left shift of 20 by 3 bits",np.left_shift(20, 3))
print("Binary representation of 20 in 8 bits",np.binary_repr(20, 8))
print("Binary representation of 160 in 8 bits",np.binary_repr(160,8))
Output:
left shift of 20 by 3 bits 160
Binary representation of 20 in 8 bits 00010100
Binary representation of 160 in 8 bits 10100000
Right Shift Operation
It shifts the bits in the binary representation of the operand to the right by the specified position. An equal number
of 0s are appended from the left. Consider the following example.
Example
import numpy as np
print("left shift of 20 by 3 bits",np.right_shift(20, 3))
print("Binary representation of 20 in 8 bits",np.binary_repr(20, 8))
print("Binary representation of 160 in 8 bits",np.binary_repr(160,8))
Output:
left shift of 20 by 3 bits 2
Binary representation of 20 in 8 bits 00010100
Binary representation of 160 in 8 bits 10100000
NumPy String Functions
NumPy contains the following functions for the operations on the arrays of dtype string.

SN Function Description

1 add() It is used to concatenate the corresponding array elements (strings).

2 multiply() It returns the multiple copies of the specified string, i.e., if a string 'hello' is multiplied
by 3 then, a string 'hello hello' is returned.

3 center() It returns the copy of the string where the original string is centered with the left and
right padding filled with the specified number of fill characters.

4 capitalize() It returns a copy of the original string in which the first letter of the original string is
converted to the Upper Case.

5 title() It returns the title cased version of the string, i.e., the first letter of each word of the
string is converted into the upper case.

6 lower() It returns a copy of the string in which all the letters are converted into the lower case.

7 upper() It returns a copy of the string in which all the letters are converted into the upper case.

9 split() It returns a list of words in the string.

9 splitlines() It returns the list of lines in the string, breaking at line boundaries.

10 strip() Returns a copy of the string with the leading and trailing white spaces removed.

11 join() It returns a string which is the concatenation of all the strings specified in the given
sequence.

12 replace() It returns a copy of the string by replacing all occurrences of a particular substring with
the specified one.

13 decode() It is used to decode the specified string element-wise using the specified codec.

14 encode() It is used to encode the decoded string element-wise.

numpy.char.add() method example


import numpy as np
print("Concatenating two string arrays:")
print(np.char.add(['welcome','Hi'], [' to Javatpoint', ' read python'] ))
Output:
Concatenating two string arrays:
['welcome to Javatpoint' 'Hi read python']
numpy.char.multiply() method example
import numpy as np
print("Printing a string multiple times:")
print(np.char.multiply("hello ",3))
Output:
Printing a string multiple times:
hello hello hello
numpy.char.center() method example
import numpy as np
print("Padding the string through left and right with the fill char *");
#np.char.center(string, width, fillchar)
print(np.char.center("Javatpoint", 20, '*'))
Output:
Padding the string through left and right with the fill char *
*****Javatpoint*****
numpy.char.capitalize() method example
import numpy as np
print("Capitalizing the string using capitalize()...")
print(np.char.capitalize("welcome to javatpoint"))
Output:
Capitalizing the string using capitalize()...
Welcome to javatpoint
numpy.char.title() method example
import numpy as np
print("Converting string into title cased version...")
print(np.char.title("welcome to javatpoint"))
Output:
Converting string into title cased version...
Welcome To Javatpoint
numpy.char.lower() method example
import numpy as np
print("Converting all the characters of the string into lowercase...")
print(np.char.lower("WELCOME TO JAVATPOINT"))
Output:
Converting all the characters of the string into lowercase...
welcome to javatpoint
numpy.char.upper() method example
import numpy as np
print("Converting all the characters of the string into uppercase...")
print(np.char.upper("Welcome To Javatpoint"))
Output:
Converting all the characters of the string into uppercase...
WELCOME TO JAVATPOINT
numpy.char.split() method example
import numpy as np
print("Splitting the String word by word..")
print(np.char.split("Welcome To Javatpoint"),sep = " ")
Output:
Splitting the String word by word..
['Welcome', 'To', 'Javatpoint']
numpy.char.splitlines() method example
import numpy as np
print("Splitting the String line by line..")
print(np.char.splitlines("Welcome\nTo\nJavatpoint"))
Output:
Splitting the String line by line..
['Welcome', 'To', 'Javatpoint']
numpy.char.strip() method example
import numpy as np
str = " welcome to javatpoint "
print("Original String:",str)
print("Removing the leading and trailing whitespaces from the string")
print(np.char.strip(str))
Output:
Original String: welcome to javatpoint
Removing the leading and trailing whitespaces from the string
welcome to javatpoint
numpy.char.join() method example
import numpy as np
print(np.char.join(':','HM'))
Output:
H:M
numpy.char.replace() method example
import numpy as np
str = "Welcome to Javatpoint"
print("Original String:",str)
print("Modified String:",end=" ")
print(np.char.replace(str, "Welcome to","www."))
Output:
Original String: Welcome to Javatpoint
Modified String: www. Javatpoint
numpy.char.encode() and decode() method example
import numpy as np
enstr = np.char.encode("welcome to javatpoint", 'cp500')
dstr =np.char.decode(enstr, 'cp500')
print(enstr)
print(dstr)
Output:
b'\xa6\x85\x93\x83\x96\x94\x85@\xa3\x96@\x91\x81\xa5\x81\xa3\x97\x96\x89\x95\xa3'
welcome to javatpoint

NumPy Copies and Views


The copy of an input array is physically stored at some other location and the content stored
at that particular location is returned which is the copy of the input array whereas the
different view of the same memory location is returned in the case of view.
In this section of the tutorial, we will consider the way by which, the different copies and
views are generated from some memory location.
Array Assignment
The assignment of a numpy array to another array doesn't make the direct copy of the original
array, instead, it makes another array with the same content and same id. It represents the
reference to the original array. Changes made on this reference are also reflected in the
original array.
The id() function returns the universal identifier of the array similar to the pointer in C.
Consider the following example.
Example
import numpy as np
a = np.array([[1,2,3,4],[9,0,2,3],[1,2,3,19]])
print("Original Array:\n",a)
print("\nID of array a:",id(a))
b=a
print("\nmaking copy of the array a")
print("\nID of b:",id(b))
b.shape = 4,3;
print("\nChanges on b also reflect to a:")
print(a)
Output:
Original Array:
[[ 1 2 3 4]
[ 9 0 2 3]
[ 1 2 3 19]]

ID of array a: 139663602288640
making copy of the array a
ID of b: 139663602288640
Changes on b also reflect to a:
[[ 1 2 3]
[ 4 9 0]
[ 2 3 1]
[ 2 3 19]]
ndarray.view() method
The ndarray.view() method returns the new array object which contains the same content as
the original array does. Since it is a new array object, changes made on this object do not
reflect the original array.
Consider the following example.
Example
import numpy as np
a = np.array([[1,2,3,4],[9,0,2,3],[1,2,3,19]])
print("Original Array:\n",a)
print("\nID of array a:",id(a))
b = a.view()
print("\nID of b:",id(b))
print("\nprinting the view b")
print(b)
b.shape = 4,3;
print("\nChanges made to the view b do not reflect a")
print("\nOriginal array \n",a)
print("\nview\n",b)
Output:
Original Array:
[[ 1 2 3 4]
[ 9 0 2 3]
[ 1 2 3 19]]

ID of array a: 140280414447456
ID of b: 140280287000656
printing the view b
[[ 1 2 3 4]
[ 9 0 2 3]
[ 1 2 3 19]]

Changes made to the view b do not reflect a


Original array
[[ 1 2 3 4]
[ 9 0 2 3]
[ 1 2 3 19]]

view
[[ 1 2 3]
[ 4 9 0]
[ 2 3 1]
[ 2 3 19]]
ndarray.copy() method
It returns the deep copy of the original array which doesn't share any memory with the
original array. The modification made to the deep copy of the original array doesn't reflect
the original array.
Consider the following example.
Example
import numpy as np
a = np.array([[1,2,3,4],[9,0,2,3],[1,2,3,19]])
print("Original Array:\n",a)
print("\nID of array a:",id(a))
b = a.copy()
print("\nID of b:",id(b))
print("\nprinting the deep copy b")
print(b)
b.shape = 4,3;
print("\nChanges made to the copy b do not reflect a")
print("\nOriginal array \n",a)
print("\nCopy\n",b)
Output:
Original Array:
[[ 1 2 3 4]
[ 9 0 2 3]
[ 1 2 3 19]]

ID of array a: 139895697586176
ID of b: 139895570139296
printing the deep copy b
[[ 1 2 3 4]
[ 9 0 2 3]
[ 1 2 3 19]]

Changes made to the copy b do not reflect a


Original array
[[ 1 2 3 4]
[ 9 0 2 3]
[ 1 2 3 19]]

Copy
[[ 1 2 3]
[ 4 9 0]
[ 2 3 1]
[ 2 3 19]]

Mathematical functions
Trigonometric functions
sin (x, /[, out, where, casting, order, ...]) Trigonometric sine, element-wise.
cos (x, /[, out, where, casting, order, ...]) Cosine element-wise.
tan (x, /[, out, where, casting, order, ...]) Compute tangent element-wise.
arcsin (x, /[, out, where, casting, order, ...]) Inverse sine, element-wise.
arccos (x, /[, out, where, casting, order, ...]) Trigonometric inverse cosine, element-wise.
arctan (x, /[, out, where, casting, order, ...]) Trigonometric inverse tangent, element-wise.
Given the “legs” of a right triangle, return its
hypot (x1, x2, /[, out, where, casting, ...])
hypotenuse.
Element-wise arc tangent of x1/x2 choosing the
arctan2 (x1, x2, /[, out, where, casting, ...])
quadrant correctly.
degrees (x, /[, out, where, casting, order, ...]) Convert angles from radians to degrees.
radians (x, /[, out, where, casting, order, ...]) Convert angles from degrees to radians.
Unwrap by changing deltas between values to 2*pi
unwrap (p[, discont, axis])
complement.
deg2rad (x, /[, out, where, casting, order, ...]) Convert angles from degrees to radians.
rad2deg (x, /[, out, where, casting, order, ...]) Convert angles from radians to degrees.
Hyperbolic functions
sinh (x, /[, out, where, casting, order, ...]) Hyperbolic sine, element-wise.
cosh (x, /[, out, where, casting, order, ...]) Hyperbolic cosine, element-wise.
tanh (x, /[, out, where, casting, order, ...]) Compute hyperbolic tangent element-wise.
arcsinh (x, /[, out, where, casting, order, ...]) Inverse hyperbolic sine element-wise.
arccosh (x, /[, out, where, casting, order, ...]) Inverse hyperbolic cosine, element-wise.
arctanh (x, /[, out, where, casting, order, ...]) Inverse hyperbolic tangent element-wise.

Rounding
around (a[, decimals, out]) Evenly round to the given number of decimals.
round_ (a[, decimals, out]) Round an array to the given number of decimals.
rint (x, /[, out, where, casting, order, ...]) Round elements of the array to the nearest integer.
fix (x[, out]) Round to nearest integer towards zero.
floor (x, /[, out, where, casting, order, ...]) Return the floor of the input, element-wise.
ceil (x, /[, out, where, casting, order, ...]) Return the ceiling of the input, element-wise.
Return the truncated value of the input, element-
trunc (x, /[, out, where, casting, order, ...])
wise.

Sums, products, differences


prod (a[, axis, dtype, out, keepdims]) Return the product of array elements over a given axis.
sum (a[, axis, dtype, out, keepdims]) Sum of array elements over a given axis.
Return the product of array elements over a given axis
nanprod (a[, axis, dtype, out, keepdims])
treating Not a Numbers (NaNs) as ones.
Return the sum of array elements over a given axis
nansum (a[, axis, dtype, out, keepdims])
treating Not a Numbers (NaNs) as zero.
Return the cumulative product of elements along a
cumprod (a[, axis, dtype, out])
given axis.
Return the cumulative sum of the elements along a
cumsum (a[, axis, dtype, out])
given axis.
Return the cumulative product of array elements over a
nancumprod (a[, axis, dtype, out])
given axis treating Not a Numbers (NaNs) as one.
Return the cumulative sum of array elements over a
nancumsum (a[, axis, dtype, out])
given axis treating Not a Numbers (NaNs) as zero.
diff (a[, n, axis]) Calculate the n-th discrete difference along given axis.
The differences between consecutive elements of an
ediff1d (ary[, to_end, to_begin])
array.
gradient (f, *varargs, **kwargs) Return the gradient of an N-dimensional array.
cross (a, b[, axisa, axisb, axisc, axis]) Return the cross product of two (arrays of) vectors.
Integrate along the given axis using the composite
trapz (y[, x, dx, axis])
trapezoidal rule.
Exponents and logarithms
Calculate the exponential of all elements in the
exp (x, /[, out, where, casting, order, ...])
input array.
expm1 (x, /[, out, where, casting, order, ...]) Calculate exp(x) - 1 for all elements in the array.
exp2 (x, /[, out, where, casting, order, ...]) Calculate 2**p for all p in the input array.
log (x, /[, out, where, casting, order, ...]) Natural logarithm, element-wise.
Return the base 10 logarithm of the input array,
log10 (x, /[, out, where, casting, order, ...])
element-wise.
log2 (x, /[, out, where, casting, order, ...]) Base-2 logarithm of x.
Return the natural logarithm of one plus the input
log1p (x, /[, out, where, casting, order, ...])
array, element-wise.
Logarithm of the sum of exponentiations of the
logaddexp (x1, x2, /[, out, where, casting, ...])
inputs.
Logarithm of the sum of exponentiations of the
logaddexp2 (x1, x2, /[, out, where, casting, ...])
inputs in base-2.

Other special functions


i0 (x) Modified Bessel function of the first kind, order 0.
sinc (x) Return the sinc function.

Floating point routines


Returns element-wise True where signbit is set
signbit (x, /[, out, where, casting, order, ...])
(less than zero).
copysign (x1, x2, /[, out, where, casting, ...]) Change the sign of x1 to that of x2, element-wise.
Decompose the elements of x into mantissa and
frexp (x[, out1, out2], / [[, out, where, ...])
twos exponent.
ldexp (x1, x2, /[, out, where, casting, ...]) Returns x1 * 2**x2, element-wise.
Return the next floating-point value after x1
nextafter (x1, x2, /[, out, where, casting, ...])
towards x2, element-wise.
Return the distance between x and the nearest
spacing (x, /[, out, where, casting, order, ...])
adjacent number.

Arithmetic operations
add (x1, x2, /[, out, where, casting, order, ...]) Add arguments element-wise.
Return the reciprocal of the argument, element-
reciprocal (x, /[, out, where, casting, ...])
wise.
negative (x, /[, out, where, casting, order, ...]) Numerical negative, element-wise.
multiply (x1, x2, /[, out, where, casting, ...]) Multiply arguments element-wise.
divide (x1, x2, /[, out, where, casting, ...]) Divide arguments element-wise.
First array elements raised to powers from second
power (x1, x2, /[, out, where, casting, ...])
array, element-wise.
subtract (x1, x2, /[, out, where, casting, ...]) Subtract arguments, element-wise.
Returns a true division of the inputs, element-
true_divide (x1, x2, /[, out, where, ...])
wise.
Return the largest integer smaller or equal to the
floor_divide (x1, x2, /[, out, where, ...])
division of the inputs.
First array elements raised to powers from second
float_power (x1, x2, /[, out, where, ...])
array, element-wise.
fmod (x1, x2, /[, out, where, casting, ...]) Return the element-wise remainder of division.
mod (x1, x2, /[, out, where, casting, order, ...]) Return element-wise remainder of division.
Return the fractional and integral parts of an
modf (x[, out1, out2], / [[, out, where, ...])
array, element-wise.
remainder (x1, x2, /[, out, where, casting, ...]) Return element-wise remainder of division.
Return element-wise quotient and remainder
divmod (x1, x2[, out1, out2], / [[, out, ...])
simultaneously.

Handling complex numbers


angle (z[, deg]) Return the angle of the complex argument.
real (val) Return the real part of the complex argument.
imag (val) Return the imaginary part of the complex argument.
conj (x, /[, out, where, casting, order, ...]) Return the complex conjugate, element-wise.

Miscellaneous
Returns the discrete, linear convolution of two
convolve (a, v[, mode])
one-dimensional sequences.
clip (a, a_min, a_max[, out]) Clip (limit) the values in an array.
Return the positive square-root of an array,
sqrt (x, /[, out, where, casting, order, ...])
element-wise.
cbrt (x, /[, out, where, casting, order, ...]) Return the cube-root of an array, element-wise.
square (x, /[, out, where, casting, order, ...]) Return the element-wise square of the input.
absolute (x, /[, out, where, casting, order, ...]) Calculate the absolute value element-wise.
fabs (x, /[, out, where, casting, order, ...]) Compute the absolute values element-wise.
Returns an element-wise indication of the sign of
sign (x, /[, out, where, casting, order, ...])
a number.
heaviside (x1, x2, /[, out, where, casting, ...]) Compute the Heaviside step function.
maximum (x1, x2, /[, out, where, casting, ...]) Element-wise maximum of array elements.
minimum (x1, x2, /[, out, where, casting, ...]) Element-wise minimum of array elements.
fmax (x1, x2, /[, out, where, casting, ...]) Element-wise maximum of array elements.
fmin (x1, x2, /[, out, where, casting, ...]) Element-wise minimum of array elements.
nan_to_num (x[, copy]) Replace nan with zero and inf with finite numbers.
If complex input returns a real array if complex
real_if_close (a[, tol])
parts are close to zero.
interp (x, xp, fp[, left, right, period]) One-dimensional linear interpolation.
Statistics
Order statistics
Return the minimum of an array or minimum along
amin(a[, axis, out, keepdims, initial])
an axis.
Return the maximum of an array or maximum
amax(a[, axis, out, keepdims, initial])
along an axis.
Return minimum of an array or minimum along an
nanmin(a[, axis, out, keepdims])
axis, ignoring any NaNs.
Return the maximum of an array or maximum
nanmax(a[, axis, out, keepdims])
along an axis, ignoring any NaNs.
Range of values (maximum - minimum) along an
ptp(a[, axis, out, keepdims])
axis.
Compute the q-th percentile of the data along the
percentile(a, q[, axis, out, …])
specified axis.
Compute the qth percentile of the data along the
nanpercentile(a, q[, axis, out, …])
specified axis, while ignoring nan values.
Compute the q-th quantile of the data along the
quantile(a, q[, axis, out, overwrite_input, …])
specified axis.
Compute the qth quantile of the data along the
nanquantile(a, q[, axis, out, …])
specified axis, while ignoring nan values.

Averages and variances


median(a[, axis, out, overwrite_input, keepdims]) Compute the median along the specified axis.
Compute the weighted average along the
average(a[, axis, weights, returned])
specified axis.
Compute the arithmetic mean along the
mean(a[, axis, dtype, out, keepdims])
specified axis.
Compute the standard deviation along the
std(a[, axis, dtype, out, ddof, keepdims])
specified axis.
var(a[, axis, dtype, out, ddof, keepdims]) Compute the variance along the specified axis.
Compute the median along the specified axis,
nanmedian(a[, axis, out, overwrite_input, …])
while ignoring NaNs.
Compute the arithmetic mean along the
nanmean(a[, axis, dtype, out, keepdims])
specified axis, ignoring NaNs.
Compute the standard deviation along the
nanstd(a[, axis, dtype, out, ddof, keepdims])
specified axis, while ignoring NaNs.
Compute the variance along the specified axis,
nanvar(a[, axis, dtype, out, ddof, keepdims])
while ignoring NaNs.

Correlating
Return Pearson product-moment correlation
corrcoef(x[, y, rowvar, bias, ddof])
coefficients.
correlate(a, v[, mode]) Cross-correlation of two 1-dimensional sequences.
cov(m[, y, rowvar, bias, ddof, fweights, …]) Estimate a covariance matrix, given data and weights.
Histograms
histogram(a[, bins, range, normed, weights, …]) Compute the histogram of a set of data.
Compute the bi-dimensional histogram of two
histogram2d(x, y[, bins, range, normed, …])
data samples.
Compute the multidimensional histogram of
histogramdd(sample[, bins, range, normed, …])
some data.
Count number of occurrences of each value in
bincount(x[, weights, minlength])
array of non-negative ints.
Function to calculate only the edges of the bins
histogram_bin_edges(a[, bins, range, weights])
used by the histogramfunction.
Return the indices of the bins to which each
digitize(x, bins[, right])
value in input array belongs.

Sorting, searching, and counting


Sorting
sort(a[, axis, kind, order]) Return a sorted copy of an array.
lexsort(keys[, axis]) Perform an indirect stable sort using a sequence of keys.
argsort(a[, axis, kind, order]) Returns the indices that would sort an array.
ndarray.sort([axis, kind, order]) Sort an array, in-place.
msort(a) Return a copy of an array sorted along the first axis.
Sort a complex array using the real part first, then the
sort_complex(a)
imaginary part.
partition(a, kth[, axis, kind, order]) Return a partitioned copy of an array.
Perform an indirect partition along the given axis using
argpartition(a, kth[, axis, kind, order])
the algorithm specified by the kind keyword.

Searching
argmax(a[, axis, out]) Returns the indices of the maximum values along an axis.
Return the indices of the maximum values in the specified axis
nanargmax(a[, axis])
ignoring NaNs.
argmin(a[, axis, out]) Returns the indices of the minimum values along an axis.
Return the indices of the minimum values in the specified axis
nanargmin(a[, axis])
ignoring NaNs.
Find the indices of array elements that are non-zero, grouped
argwhere(a)
by element.
nonzero(a) Return the indices of the elements that are non-zero.
flatnonzero(a) Return indices that are non-zero in the flattened version of a.
where(condition, [x, y]) Return elements, either from x or y, depending on condition.
Find indices where elements should be inserted to maintain
searchsorted(a, v[, side, sorter])
order.
extract(condition, arr) Return the elements of an array that satisfy some condition.

Counting
count_nonzero(a[, axis]) Counts the number of non-zero values in the array a.
Linear algebra (numpy.linalg)
Matrix and vector products
dot(a, b[, out]) Dot product of two arrays.
Compute the dot product of two or more arrays
linalg.multi_dot(arrays) in a single function call, while automatically
selecting the fastest evaluation order.
vdot(a, b) Return the dot product of two vectors.
inner(a, b) Inner product of two arrays.
outer(a, b[, out]) Compute the outer product of two vectors.
matmul(x1, x2, /[, out, casting, order, …]) Matrix product of two arrays.
Compute tensor dot product along specified
tensordot(a, b[, axes])
axes for arrays >= 1-D.
Evaluates the Einstein summation convention
einsum(subscripts, *operands[, out, dtype, …])
on the operands.
Evaluates the lowest cost contraction order for
einsum_path(subscripts, *operands[, optimize]) an einsum expression by considering the
creation of intermediate arrays.
linalg.matrix_power(a, n) Raise a square matrix to the (integer) power n.
kron(a, b) Kronecker product of two arrays.

Decompositions
linalg.cholesky(a) Cholesky decomposition.
linalg.qr(a[, mode]) Compute the qr factorization of a matrix.
linalg.svd(a[, full_matrices, compute_uv]) Singular Value Decomposition.

Matrix eigenvalues
linalg.eig(a) Compute the eigenvalues and right eigenvectors of a square array.
Return the eigenvalues and eigenvectors of a complex Hermitian
linalg.eigh(a[, UPLO])
(conjugate symmetric) or a real symmetric matrix.
linalg.eigvals(a) Compute the eigenvalues of a general matrix.
Compute the eigenvalues of a complex Hermitian or real symmetric
linalg.eigvalsh(a[, UPLO])
matrix.

Norms and other numbers


linalg.norm(x[, ord, axis, keepdims]) Matrix or vector norm.
linalg.cond(x[, p]) Compute the condition number of a matrix.
linalg.det(a) Compute the determinant of an array.
linalg.matrix_rank(M[, tol, hermitian]) Return matrix rank of array using SVD method
Compute the sign and (natural) logarithm of the
linalg.slogdet(a)
determinant of an array.
trace(a[, offset, axis1, axis2, dtype, out]) Return the sum along diagonals of the array.
Solving equations and inverting matrices
Solve a linear matrix equation, or system of linear scalar
linalg.solve(a, b)
equations.
linalg.tensorsolve(a, b[, axes]) Solve the tensor equation a x = b for x.
linalg.lstsq(a, b[, rcond]) Return the least-squares solution to a linear matrix equation.
linalg.inv(a) Compute the (multiplicative) inverse of a matrix.
linalg.pinv(a[, rcond]) Compute the (Moore-Penrose) pseudo-inverse of a matrix.
linalg.tensorinv(a[, ind]) Compute the ‘inverse’ of an N-dimensional array.

Exceptions
linalg.LinAlgError Generic Python-exception-derived object raised by linalg functions.

Matrix library (numpy.matlib)


This module contains all functions in the numpy namespace, with the following replacement functions
that return matricesinstead of ndarrays.
Functions that are also in the numpy namespace and return matrices

mat(data[, dtype]) Interpret the input as a matrix.

matrix(data[, dtype, copy])

asmatrix(data[, dtype]) Interpret the input as a matrix.

bmat(obj[, ldict, gdict]) Build a matrix object from a string, nested sequence, or array.

Replacement functions in matlib


Return a new matrix of given shape and type, without initializing
empty(shape[, dtype, order])
entries.

zeros(shape[, dtype, order]) Return a matrix of given shape and type, filled with zeros.

ones(shape[, dtype, order]) Matrix of ones.

eye(n[, M, k, dtype, order]) Return a matrix with ones on the diagonal and zeros elsewhere.

identity(n[, dtype]) Returns the square identity matrix of given size.

repmat(a, m, n) Repeat a 0-D to 2-D array or matrix MxN times.

rand(*args) Return a matrix of random values with given shape.

Return a random matrix with data from the “standard normal”


randn(*args)
distribution.

Das könnte Ihnen auch gefallen