Numpy&Pandas 001: Attributes and Array in NumPy

At first, import the numpy. Normally, we will import it as np for calling it easily.

1
import numpy as np

Attributes

Using a method called array to turn a list to an array.

1
2
array = np.array([[1,2,1],
[2,1,2]])

First attribute I would like to talk about is the dimension of the array.

1
array.ndim	#2

Second is the number of rows and columns of the array.

1
array.shape #(2,3)

Last is the number of the array.

1
array.size	#6

Array

We have already known how we make an array. Let us see more things on Array.

Data type

We can figure a type of data when we make it.

1
2
a1 = np.array([2,22,222],dtype=np.int16)
a1.dtype #dtype('int16')

It also have others type. For example, int32, float64…

Initial Array

It support some special types to make an array quickly, because of the unknown value(fixed size) sometimes we need.

Firstly, we can initial a zero array, we need input a shape of the array.

1
2
3
4
5
a1 = np.zeros((3,3))

#array([[0., 0., 0.],
# [0., 0., 0.],
# [0., 0., 0.]])

Also, we can initial a one array

1
2
3
4
5
a2 = np.ones((3,4),dtype=np.int)

#array([[1, 1, 1, 1],
# [1, 1, 1, 1],
# [1, 1, 1, 1]])

Besides, empty. But for here it will generate the number that is very close to zero.

1
2
3
4
5
6
7
a3 = np.empty((2,2,2))

#array([[[0.00000000e+000, 0.00000000e+000],
# [0.00000000e+000, 0.00000000e+000]],
#
# [[0.00000000e+000, 5.90902512e-321],
# [1.37961438e-306, 2.22522596e-306]]])

There is a method, which is likely to range() (the method in Python)

1
2
3
a4 = np.arange(1,10,3) #from 1 to 9 and 3 intervals

#array([1, 4, 7])

And we can change the shape of it, from 1-dim to 2-dim or 3. Be careful, you should think a little bit more about the struct of the new shape.

1
2
3
4
a5 = np.arange(10).reshape((2,5))

#array([[0, 1, 2, 3, 4],
# [5, 6, 7, 8, 9]])

Besides, there is another one like arange, it is linspace()

1
2
3
a6 = np.linspace(1,10,4) 	#from 1 to 10 and split it in 4 parts

#array([ 1., 4., 7., 10.])

We can also change the shape of it.

Thanks for your reading, I hope it is useful for you.


End

Illustrator / Cagy

Text / Cagy

Editor / Cagy

Design / Cagy