Data Types in NumPy
NumPy has some extra data types, and refer to data types with one
character, like i for integers, u for unsigned integers etc.
Below is a list of all data types in NumPy and the characters used to
represent them.
i - integer
b - boolean
u - unsigned integer
f - float
c - complex float
m - timedelta
M - datetime
O - object
S - string
U - unicode string
V - fixed chunk of memory for other type ( void )
Checking the Data Type of an Array
The NumPy array object has a property called dtype that returns the data
type of the array:
ExampleGet your own Python Server
Get the data type of an array object:
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr.dtype)
output
int64
Example
Get the data type of an array containing strings:
import numpy as np
arr = np.array(['apple', 'banana', 'cherry'])
print(arr.dtype)
output :
<U6
Creating Arrays With a Defined Data Type
We use the array() function to create arrays, this function can take an
optional argument: dtype that allows us to define the expected data type of
the array elements:
Example
Create an array with data type string:
import numpy as np
arr = np.array([1, 2, 3, 4], dtype='S')
print(arr)
print(arr.dtype)
output:
[b'1' b'2' b'3' b'4']
|S1
For i, u, f, S and U we can define size as well.
Example
Create an array with data type 4 bytes integer:
import numpy as np
arr = np.array([1, 2, 3, 4], dtype='i4')
print(arr)
print(arr.dtype)
output:
[1 2 3 4]
int32
A non integer string like 'a' can not be converted to integer (will
raise an error):
import numpy as np
arr = np.array(['a', '2', '3'], dtype='i')
output:
Traceback (most recent call last):
File "./prog.py", line 3, in
ValueError: invalid literal for int() with base 10: 'a'
Converting Data Type on Existing Arrays
The best way to change the data type of an existing array, is to make a copy
of the array with the astype() method.
The astype() function creates a copy of the array, and allows you to specify
the data type as a parameter.
The data type can be specified using a string, like 'f' for float, 'i' for integer
etc. or you can use the data type directly like float for float and int for
integer.
Example
Change data type from float to integer by using 'i' as parameter value:
import numpy as np
arr = np.array([1.1, 2.1, 3.1])
newarr = arr.astype('i')
print(newarr)
print(newarr.dtype)
output:
[1 2 3]
int32
Change data type from float to integer by using int as parameter
value:
import numpy as np
arr = np.array([1.1, 2.1, 3.1])
newarr = arr.astype(int)
print(newarr)
print(newarr.dtype)
output:
[1 2 3]
int64
Change data type from integer to boolean:
import numpy as np
arr = np.array([1, 0, 3])
newarr = arr.astype(bool)
print(newarr)
print(newarr.dtype)
[ True False True]
bool
arithmetic operations using NumPy.
Addition
Python3
import numpy as np
# Defining both the matrices
a = np.array([5, 72, 13, 100])
b = np.array([2, 5, 10, 30])
# Performing addition using arithmetic operator
add_ans = a+b
print(add_ans)
# Performing addition using numpy function
add_ans = np.add(a, b)
print(add_ans)
# The same functions and operations can be used for multiple matrices
c = np.array([1, 2, 3, 4])
add_ans = a+b+c
print(add_ans)
add_ans = np.add(a, b, c)
print(add_ans)
Output
[ 7 77 23 130]
[ 7 77 23 130]
[ 8 79 26 134]
[ 8 79 26 134]
As we can see that the matrixes are of the same shape, if they are different
than, Numpy will try broadcasting if it is possible. The reader can see that the
same operation (addition) can be done using arithmetic operation (+) as well
as numpy function (np.add).
Subtraction
Python3
import numpy as np
# Defining both the matrices
a = np.array([5, 72, 13, 100])
b = np.array([2, 5, 10, 30])
# Performing subtraction using arithmetic operator
sub_ans = a-b
print(sub_ans)
# Performing subtraction using numpy function
sub_ans = np.subtract(a, b)
print(sub_ans)
Output
[ 3 67 3 70]
[ 3 67 3 70]
The user can also perform broadcasting with a matrix and a constant
Python3
import numpy as np
# Defining both the matrices
a = np.array([5, 72, 13, 100])
b = np.array([2, 5, 10, 30])
# Performing subtraction using arithmetic operator
sub_ans = a-b-1
print(sub_ans)
# Performing subtraction using numpy function
sub_ans = np.subtract(a, b, 1)
print(sub_ans)
Output
[ 2 66 2 69]
[ 2 66 2 69]
Multiplication
Python3
import numpy as np
# Defining both the matrices
a = np.array([5, 72, 13, 100])
b = np.array([2, 5, 10, 30])
# Performing multiplication using arithmetic operator
mul_ans = a*b
print(mul_ans)
# Performing multiplication using numpy function
mul_ans = np.multiply(a, b)
print(mul_ans)
Output
[ 10 360 130 3000]
[ 10 360 130 3000]
Division
Python3
import numpy as np
# Defining both the matrices
a = np.array([5, 72, 13, 100])
b = np.array([2, 5, 10, 30])
# Performing division using arithmetic operators
div_ans = a/b
print(div_ans)
# Performing division using numpy functions
div_ans = np.divide(a, b)
print(div_ans)
Output
[ 2.5 14.4 1.3 3.33333333]
[ 2.5 14.4 1.3 3.33333333]
There is a myriad number of other functions which in NumPy let us see some
of them one by one.
mod() and power() function
Example
Python3
# Performing mod on two matrices
mod_ans = np.mod(a, b)
print(mod_ans)
#Performing remainder on two matrices
rem_ans=np.remainder(a,b)
print(rem_ans)
# Performing power of two matrices
pow_ans = np.power(a, b)
print(pow_ans)
Output
[ 1 2 3 10]
[ 1 2 3 10]
[ 25 1934917632 137858491849
1152921504606846976]
Some aggregation and statistical functions
Example
Python3
# Getting mean of all numbers in 'a'
mean_a = np.mean(a)
print(mean_a)
# Getting average of all numbers in 'b'
mean_b = np.average(b)
print(mean_b)
# Getting sum of all numbers in 'a'
sum_a = np.sum(a)
print(sum_a)
# Getting variance of all number in 'b'
var_b = np.var(b)
print(var_b)
Output
47.5
11.75
190
119.1875