Numpy in Python (Basic-2)

Array Attributes & Array Operations

MOUMITA DEY
3 min readDec 11, 2022
source

Array Attributes

Every Numpy Array is an object of the numpy class, so when we make a numpy array, it can access some attributes from the numpy class, so we should know about some of those attributes if we want to work with data.

so first we need 3 arrays to work with.

a1 = np.arange(10)   # 1D or vector
a2 = np.arange(12,dtype=float).reshape(3,4) # 2D or matrix
a3 = np.arange(8).reshape(2,2,2) #3D or tensor

print(a1)
print(a2)
print(a3)

ndim

we can use any array to find out what is the dimension of that array. it tells if that given arrays dimension is 1D or 2D or 3D or nD.

# ndim

print(a1.ndim)
print(a2.ndim)
print(a3.ndim)
tells the dimension of the array.

shape

it tells the shape of the array for example, if it is a matrix ,it will tell you the number of rows and columns

print(a3.shape)
a3

(2,2,2)

well, it means we have a 3D array that is made with two 2D arrays and each 2D array has 2 rows and 2 columns.

it tells how many items exists in each dimension of that array

size

it tells the number of items present in the nd array

size function

itemsize

it tells the item size of the given array in bytes.

# itemsize
i1 = np.arange(10, dtype=np.int16)
i2 = np.arange(10)

print(i1)
print(i1.itemsize)
print(i2)
print(i2.itemsize)
item size of a given array

dtype

it tells datatype of items present in the nd array.

# dtype

print(a1.dtype)
print(a2.dtype)

print(i1.dtype)
datatype of items

Changing DataType

let’s say I have an nd array of datatype int64, but I don’t need this big size to store something like someones age so I can change it into int8, so it will take less space in the RAM

# astype
print(a3.dtype)
a3.astype(np.int8)

Array Operations

first, to go easy we are creating two 2D arrays a1 and a2.

a1 = np.arange(12).reshape(3,4)
a2 = np.arange(12,24).reshape(3,4)

print(a1)
print(a2)

there are 2 types of operations scalar and vector

scalar operations

arithmetic operation

any operation between a matrix and a scalar number. any operations that we have seen in python like +, -, *, /, %, ** etc.

scalar arithmetic operations

relational operation

we can see if every item present in the array passes the condition of the relational operator or not, if it passes it will say True or False otherwise.

relational operators : >, <, != , == etc.

# relational

print(a2)
a2 > 15

vector operations

basically array operations between two matrices but the shape have to be the same for both.

arithmetic operations

vector arithmetic operation
# arithmetic
print(a1)
print(a2)

print(a1 + a2)
print(a2 ** 2)

--

--