NumPy 通常与 SciPy(Scientific Python)和 Matplotlib(绘图库)一起使用, 这种组合广泛用于替代 MatLab,是一个强大的科学计算环境,有助于我们通过 Python 学习数据科学或者机器学习。

国内源安装

pip3 install numpy scipy matplotlib -i https://pypi.tuna.tsinghua.edu.cn/simple

验证是否安装成功

from numpy import *
eye(4) #对角矩阵
array([[1., 0., 0., 0.],
       [0., 1., 0., 0.],
       [0., 0., 1., 0.],
       [0., 0., 0., 1.]])

ndarray对象是用于存放同类型元素的多维数组

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

object 数组或嵌套的数列
dtype  数组元素的数据类型,可选
copy   对象是否需要复制,可选
oder   创建数组的方向,C为行方向,F为列方向,A为任意方向
subok  默认返回一个与基类类型一致的数组
ndmin  指定生成数组的最小纬度

最小纬度2维

import numpy as np
a = np.array([1, 2, 3], ndmin=2)
print(a)

#输出
[[1 2 3]]

数据类型

使用标量类型

dt = np.dtype(np.int32)
print(dt)

#输出
int32

int8、int16、int32、int64四种数据类型可以使用字符串’i1’, ’i2’, ’i4’, ’i8’表示

import numpy as np

dt = np.dtype('i8')
print(dt)

#输出
int64

将数据类型应用于ndarray对象

import  numpy as np
dt = np.dtype([('age', np.int8)])
a = np.array([(10,), (20,), (30,)], dtype=dt)
print(a)

#输出
[(10,) (20,) (30,)]

类型字段名可以用于存取实际的age列

import numpy as np
dt = np.dtype([('age', np.int8)])
a = np.array([(10,), (20,), (30,)], dtype=dt)
print(a['age'])

#输出
[10 20 30]
Categories: python

0 Comments

发表评论

Avatar placeholder

邮箱地址不会被公开。 必填项已用*标注