Data analysis--Numpy primary (1)

Numpy is the basic library for data analysis, which supports a large number of dimensional calculations and matrix operations. At the same time, it is also a very fast mathematical library, mainly used for array calculations, with functions such as linear algebra, Fourier transform, and random number generation.

Ndarray object

One of the most important features of Numpy is its N-dimensional array object ndarray, which is a collection of a series of data of the same type. To create an ndarray object, you only need to call Numpy's array function.

  • numpy.array(object, dtype=None, copy=True, order=None, subok=False, ndmin=0)
    The meanings of the parameters are as follows:
    object: array. This can be a multi-dimensional array.
    dtype: The data type of the array elements. Numpy has data types such as bool, int, uint, float, and complex.
    copy: Whether the object needs to be copied. When an array is created, a block will be copied by default to prevent insecurity.
    order: Create array style, C is the row direction, F is the column direction, A is any direction (default).
    subok: Returns an array of the same type as the base class by default.
    ndmin: Specifies the minimum dimension of the array.

Note : When the array data in the array function contains strings, integers, and floating-point numbers at the same time, if no data type is specified , it will convert all data into one data type, and the conversion priority is: string > floating-point number > integer

For example : Create a one-dimensional ndarray object, the array data contains strings, integers, and floating-point numbers, and the data type used is int type.

code show as below:

import numpy as np
ns = np.array([1,3.5,"4"],dtype=int)
ns

The result is:

insert image description here

dtype object

The numeric types of numpy are actually instances of dtpye objects, and correspond to unique characters, for example: numpy.bool, numpy.int32, numpy.float32, numpy.complex64, etc. dtype objects can be created with the dtype() function.

  • numpy.dtype(object,align,copy)
    The meanings of the parameters are as follows:
    object: The data type object to be converted to.
    align: If True, pad fields to resemble C structs.
    copy: Copy dtype object, if False it is a reference to a built-in data object.

For example: create a structured data type and apply to ndarray object.

code show as below:

import numpy as np
# student为结构化数据类型
# S为Str类型,"i1"表示int8
student = np.dtype([('name','S20'), ('age', 'i1'), ('marks', 'f4')]) 
print(student)
a = np.array([('abc', 21, 50),('xyz', 18, 75)], dtype = student) 
print(a)
# 这里的类型字段名可以保存实际的列
print("第一列",a["name"],"第二列",a["age"],"第三列",a["marks"])

The result is as follows:

insert image description here

Guess you like

Origin blog.csdn.net/m0_67021058/article/details/131036453