python numpy

If you learn python based AI software such as tensorflow, you’ll inevitably meet the package Numpy and DataFrame,etc. So you must learn how to use Numpy and DataFrame before you can dig further into the tensorflow related source code.

You can use numpy to create a ndarray object. It is a multi-dimension array. Without numpy, you can also create a multi-dimensional array using python list, like [[1,2,3],[4,5,6],[7,8,9]]. But numpy ndarray provides more methods to handle multi-dimensional array. So you’d better convert your list to a ndarray object first, then call numpy functions to handle it:

import numpy;

data = [1,2,3,4,5,6]

x = numpy.array(data)

print (x)

print (x.dtype)

print (x.ndim)

print(x.shape)

​

​

[1 2 3 4 5 6]
int32
1
(6,)

 

import numpy;

data = [[1,2],[3,4],[5,6]]

x = numpy.array(data)

print (x)

print (x.dtype)

print (x.ndim)

print(x.shape)

​

​

[[1 2]
 [3 4]
 [5 6]]
int32
2
(3, 2)

From the above code, we can know that a ndarray object can be created with the numpy.array() function, and its dtype attribute represents the data type of the data contained in it, its ndim attribute represents the number of dimensions of the multi-dimensional array and its shape attribute is a tuple that represents the sizes of each dimension of the array. We know that the elements in a list can have different types, however, the elements in a ndarray object must be the same type.

How to access an element in a ndarray? You can use x[i,j] or x[i][j]. They get the same element.x[i1:i2,j1:j2] gets the elements from row i1 to i2(not include i2), for each row, only gets the elements from column j1 to column j2(not include j2).

When a ndarray is calculated with a scalar, every element in the ndarray will be calculated with the scalar. But if a ndarray is calculated with another ndarray, only corresponding elements in the two ndarrays are calculated.

It is interesting that the index (what is in []) can also be a boolean ndarray., in which case only the elements corresponding the true elements are selected to form a new (smaller) ndarray. The index can even be an int ndarray, which indicates which elements will be selected. For example, x[[1,3]] will select the second element and the fourth element to form the new ndarray. x[[1,3],[0,1]] will select the second and the fourth rows, for the second row, only the first element is selected; for the fourth row, only the second element is selected. So x[[1,3],[0,1]] only contains two elements of the original array.

numpy.where(cond,x,y) is used to create a new ndarray based on the bool cond array. The new array has the same size as cond. If the element in the cond is true, the corresponding  element in the result array takes the value from x, otherwise, takes the value from y.

reference:https://blog.csdn.net/cxmscb/article/details/54583415

Leave a Reply