Numpy library foundation (20,190,804)

1.Numpy basic introduction

  • NumPy is a powerful Python library, mainly used to calculate multidimensional array to perform right.
  • NumPy is numerical and python Jianpin.

2. Applications

  • Machine learning models: mainly the various numerical matrix.
  • Image processing and computer graphics:
  • Mathematical tasks: integration, differentiation, interpolation, extrapolation.

3. Install

pip install numpy

 

Everything is ready, let us practice up!

 

4, NumPy   Ndarray objects

  • The most important feature is the N-dimensional array NumPy objects ndarray, which is a collection of different types of data, labeled 0 to index the start elements in a set.
  • ndarray Each element has the same size storage area in memory.
  • Internal ndarray consists of the following:
      • A pointer to data (data memory or a memory-mapped file) pointer.

      • Data type or dtype, describes a fixed grid size value in the array.

      • An array of a shape (Shape) tuples, each tuple represents the size of the dimension.

      • A span tuple (stride), wherein the forward integer refers to the number of bytes required element to a "cross" in the current dimension.

                               Span can be negative, it would be after the memory array to the mobile, slice  obj [:: - 1] or  obj [:, :: - 1] is true.

     

Create a ndarray simply call NumPy array of functions to:   

numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)

Example:

# dtype 参数  
import numpy as np 
a = np.array([1,  2,  3], dtype = complex)  
print (a)

result:

[+ 0.j 1., 2. + 0.j 3. 0.j +]

NOTE: ndarray dimensional object consists of a continuous portion of the computer memory of the composition, and the binding mode index, mapping each element into a position in the memory block. In line sequential memory blocks (C-style), or the order of columns (or the FORTRAN MatLab style, i.e. the pattern's F) to save the elements.

5, the data type

numpy supported data types than Python lot more built-in type, and may be substantially C-language data types, some of which correspond to the type of the built-in type Python. The following table lists the common NumPy basic types.

 

name description
bool_ Boolean data type (True or False)
int_ The default integer type (similar to the C language long, int32 or Int64)
intc The same type C and int, int is generally 64 or int32
intp For the integer type of the index (an ssize_t C-like, generally remains int32 or Int64)
int8 Character clause (-128 to 127)
int16 Integer (-32768 to 32767)
int32 Integer (-2147483648 to 2147483647)
int64 Integer (-9223372036854775808 to 9223372036854775807)
uint8 Unsigned integer (0 to 255)
uint16 Unsigned integer (0 to 65535)
uint32 Unsigned integer (0 to 4294967295)
uint64 Unsigned integer (0 to 18446744073709551615)
float_ float64 type of shorthand
float16 Half-precision floating-point format, comprising: a sign bit, five-bit exponent, 10 mantissa bits
float32 Single-precision floating point number, comprising: a sign bit, eight exponent, 23 mantissa bits
float64 Double precision floating point, comprising: a sign bit, 11 exponent bits, 52 bits mantissa
complex_ complex128 shorthand type, i.e., a plurality of 128-bit
complex64 Complex, 32-bit floating-point number represents bis (real number part and imaginary number part)
complex128

Complex, 64-bit floating-point number represents bis (real number part and imaginary number part)

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Data type object (dtype) (downright oh !!!)

dtype objects are constructed using the following syntax:

numpy.dtype(object, align, copy)

Example:

 

Import numpy NP AS
 # int8, Int16, Int32, Int64 four data types can use string 'i1', 'i2', 'i4', 'i8' replaced 
dt = np.dtype ( ' I4 ' )
 Print (dt)

 

Each type has a unique built-define its character code, as follows:

 

character Corresponding type
b Boolean
i (Signed) integer
in Unsigned int integer
f Float
c Plural float
m timedelta (time interval)
M datetime (date and time)
O (Python) objects
S, a (Byte-) string
The Unicode
V Raw data (void)

 

 

 

 

 

 

 

 

 

 

 

6, array property

NumPy dimension of the array are called rank (Rank), the rank of a one-dimensional array, a two-dimensional array of rank 2, and so on.

 

In NumPy, each linear array is called a shaft (Axis), that is, the dimension (dimensions). For example, the equivalent of a two-dimensional array is a two-dimensional array, where the first one-dimensional array, each element is a one-dimensional array. So is the one-dimensional array in NumPy axis (Axis), a first shaft corresponds to the underlying array, a second axis is the underlying array to array. The number of axes - rank is the dimension of the array.

 

Attributes Explanation
ndarray.ndim Rank number, i.e. the number or dimensions of shaft
ndarray.shape Dimension of an array, for the matrix, n-rows and m columns
ndarray.size The total number of array elements, corresponding to the n * m values ​​of .shape
ndarray.dtype Object element type ndarray
ndarray.itemsize Ndarray size of each element in the object, in bytes
ndarray.flags ndarray object memory information
ndarray.real The real portion of the element ndarray
ndarray.imag The imaginary part of the element ndarray
ndarray.data Buffer contains the actual array elements, since the element is generally provided by the array index is generally not required to use this property.

 

 

 

 

 

 

 

 

 

 

 

 

ndarray.flags return ndarray object memory information, comprising the following properties:

 

Attributes description
C_CONTIGUOUS (C) The data is in a single continuous segment C-style
F_CONTIGUOUS (F) The data is in a single continuous segment of the Fortran-style
OWNDATA (O) Has an array of memory it uses or borrow it from another object
WRITEABLE (W) May be written to the data area, and the value is set to False, then the data is read-only
ALIGNED (A) And the data elements are all properly aligned to the hardware
UPDATEIFCOPY (U) This array is a copy of the other array, when the array is released, the original contents of the array will be updated

 

 

 

 

 

 

 

 

 

 

7, create an array

In addition to using the underlying array ndarray ndarray configured to create, but also can be created in several ways.

7.1  numpy.empty

 

numpy.empty(shape, dtype = float, order = 'C')

 

 

参数 描述
shape 数组形状
dtype 数据类型,可选
order 有"C"和"F"两个选项,分别代表,行优先和列优先,在计算机内存中的存储元素的顺序。

 

 

 

 

示例: 

 
 
import numpy as np
x = np.empty([3,2], dtype = int)
print ("x =" ,x)

结果:

注意 − 数组元素为随机值,因为它们未初始化。

 

7.2 numpy.zeros

 

numpy.zeros(shape, dtype = float, order = 'C')

 

 

参数 描述
shape 数组形状
dtype 数据类型,可选
order 'C' 用于 C 的行数组,或者 'F' 用于 FORTRAN 的列数组

 

 

 

 

 

import numpy as np
 
# 默认为浮点数
x = np.zeros(5) 
print(x)
 
# 设置类型为整数
y = np.zeros((5,), dtype = np.int) 
print(y)

7.3  numpy.ones

 

numpy.ones(shape, dtype = None, order = 'C')

 

 

参数 描述
shape 数组形状
dtype 数据类型,可选
order 'C' 用于 C 的行数组,或者 'F' 用于 FORTRAN 的列数组

 

 

 

 

import numpy as np
 
# 默认为浮点数
x = np.ones(5) 
print(x)
 
# 自定义类型
x = np.ones([2,2], dtype = int)
print(x)

 

 

8、NumPy 从已有的数组创建数组

8.1 numpy.asarray

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

 

 

参数 描述
a 任意形式的输入参数,可以是,列表, 列表的元组, 元组, 元组的元组, 元组的列表,多维数组
dtype 数据类型,可选
order 可选,有"C"和"F"两个选项,分别代表,行优先和列优先,在计算机内存中的存储元素的顺序。

 

 

 

 

 

8.2 numpy.frombuffer

 

numpy.frombuffer 用于实现动态数组。

 

numpy.frombuffer 接受 buffer 输入参数,以流的形式读入转化成 ndarray 对象。

numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0)

注意:buffer 是字符串的时候,Python3 默认 str 是 Unicode 类型,所以要转成 bytestring 在原 str 前加上 b。

 

 

参数 描述
buffer 可以是任意对象,会以流的形式读入。
dtype 返回数组的数据类型,可选
count 读取的数据数量,默认为-1,读取所有数据。
offset 读取的起始位置,默认为0。

 

 

 

 

 

 

 

 pytnon 3.x:

import numpy as np 
 
s =  b'Hello World' 
a = np.frombuffer(s, dtype =  'S1')  
print (a)

 

结果:

 

8.3 numpy.fromiter

numpy.fromiter 方法从可迭代对象中建立 ndarray 对象,返回一维数组。

numpy.fromiter(iterable, dtype, count=-1)

 

 

参数 描述
iterable 可迭代对象
dtype 返回数组的数据类型
count 读取的数据数量,默认为-1,读取所有数据

 

 

 

 

 

 

import numpy as np 
 
# 使用 range 函数创建列表对象  
list=range(5)
it=iter(list)
 
# 使用迭代器创建 ndarray 
x=np.fromiter(it, dtype=float)
print(x)

结果:

 

9、NumPy 从数值范围创建数组

9.1 numpy.arange

 

numpy.arange(start, stop, step, dtype)

 

 

参数 描述
start 起始值,默认为0
stop 终止值(不包含)
step 步长,默认为1
dtype 返回ndarray的数据类型,如果没有提供,则会使用输入数据的类型。

 

 

 

 

 

 

 

 

import numpy as np
 
# 设置了 dtype
x = np.arange(5, dtype =  float)  
print (x)

  结果:

 

9.2  numpy.linspace

numpy.linspace 函数用于创建一个一维数组,数组是一个等差数列构成的;

 

np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)

 

 

参数 描述
start 序列的起始值
stop 序列的终止值,如果endpointtrue,该值包含于数列中
num 要生成的等步长的样本数量,默认为50
endpoint 该值为 ture 时,数列中中包含stop值,反之不包含,默认是True。
retstep 如果为 True 时,生成的数组中会显示间距,反之不显示。
dtype ndarray 的数据类型

 

 

 

 

 

 

 

 

import numpy as np
a =np.linspace(1,10,10,retstep= True)   #显示步长
 
print(a)
# 拓展例子
b =np.linspace(1,10,10).reshape([10,1])
print(b)

  结果:

 

9.3 numpy.logspace

numpy.logspace 函数用于创建一个于等比数列。

 

 

np.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)

 

 

参数 描述
start 序列的起始值为:base ** start
stop 序列的终止值为:base ** stop。如果endpointtrue,该值包含于数列中
num 要生成的等步长的样本数量,默认为50
endpoint 该值为 ture 时,数列中中包含stop值,反之不包含,默认是True。
base 对数 log 的底数。(默认是10)
dtype ndarray 的数据类型

 

 

 

 

 

 

 

import numpy as np
a = np.logspace(0,9,10,base=2)
print (a)

结果:

2的0次方;2的1次方;2的2次方;2的3次方;。。。;2的9次方。

 

 

Guess you like

Origin www.cnblogs.com/bltstop/p/11300517.html