You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

149 lines
4.3 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# 2.1.1ndarray对象
## 怎样安装 NumPy
NumPy (Numerical Python) 是 Python 语言的一个扩展程序库,支持大量的维度数组与矩阵运算,此外也针对数组运算提供大量的数学函数库。是在学习机器学习、深度学习之前应该掌握的一个非常基本且实用的 python 库。
想要安装 NumPy 其实非常简单,进入命令行,输入如下代码即可:
```shell
pip install numpy
```
## 什么是 ndarray 对象
NumPy 为什么能够受到各个数据科学从业人员的青睐与追捧,其实很大程度上是因为 NumPy 在向量计算方面做了很多优化,接口也非常友好。而这些其实都是在围绕着 NumPy 的一个核心数据结构 ndarray 。
ndarray 的全称是 N-Dimension Arrary ,字面意义上其实已经表明了一个 ndarray 对象就是一个 N 维数组。但要注意的是ndarray 是**同质**的。同质的意思就是说** N 维数组里的所有元素必须是属于同一种数据类型的**。**(PS: python 中的 list 是异质的)**
ndarray 对象实例化好了之后,包含了一些基本的属性。比如 shape ndim size dtype 。其中:
- shape : ndarray 对象的形状,由一个 tuple 表示
- ndim : ndarray 对象的维度
- size : ndarray 对象中元素的数量
- dtype : ndarray 对象中元素的数据类型,例如 int64 float32 等。
来看个例子,假设现在有一个 3 行 5 列的矩阵( ndarray )如下:
```python
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
```
那么该 ndarray 的 shape 是 (3, 5) 。(代表 3 行 5 列)ndim 是 2 (因为矩阵有行和列两个维度)size 是 15 (因为矩阵总共有 15 个元素) dtype 是 int32 (因为矩阵中元素都是整数,并且用 32 位整型足够表示矩阵中的元素)
打印这些属性的示例代码如下:
```python
# 导入numpy并取别名为np
import numpy as np
# 构造ndarray
a = np.arange(15).reshape(3, 5)
# 打印a的shapendimsizedtype
print(a.shape)
print(a.ndim)
print(a.size)
print(a.dtype)
```
输出如下:
```python
(3, 5)
2
15
int32
```
## 如何实例化 ndarray 对象
实例化 ndarray 对象的函数有很多种,但最为常用的函数是 array zeros ones 以及 empty 。
### 使用 array 函数实例化 ndarray 对象
如果你手头上有一个 python 的 list ,想要将这个 list 转成 ndarray ,此时可以使用 NumPy 中的 array 函数将 list 中的值作为初始值,来实例化一个 ndarray 对象。代码如下:
```python
import numpy as np
# 使用列表作为初始值实例化ndarray对象a
a = np.array([2,3,4])
# 打印ndarray对象a
print(a)
```
输出如下:
```python
[2, 3, 4]
```
### 使用 zeros ones empty 函数实例化 ndarray 对象
通常在写代码的时候,数组中元素的值一般都喜欢先初始化成 0 ,如果使用 array 的方式实例化 ndarray 对象的话,虽然能实现功能,但显得很麻烦(**首先要有一个全是 0 的 list**)。那有没有简单粗暴的方式呢,有!!那就是 zeros 函数,你只需要把 ndarray 的 shape 作为参数传进去即可。代码如下:
```python
import numpy as np
# 实例化ndarray对象aa是一个3行4列的矩阵矩阵中元素全为0
a = np.zeros((3, 4))
# 打印ndarray对象a
print(a)
```
输出如下:
```python
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
```
如果想把数组中的元素全部初始化成 1 ,聪明的你应该能想到就是用 ones 函数oens 的用法与 zeros 一致。代码如下:
```python
import numpy as np
# 实例化ndarray对象aa是一个3行4列的矩阵矩阵中元素全为1
a = np.ones((3, 4))
# 打印ndarray对象a
print(a)
```
输出如下:
```python
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
```
如果 01大法 满足不了你,想要用随机值作为初始值来实例化 ndarray 对象empty 函数能够满足你。 empty 的使用方式与 zeros 和 ones 如出一辙,代码如下:
```python
import numpy as np
# 实例化ndarray对象aa是一个2行3列的矩阵矩阵中元素全为随机值
a = np.empty((2, 3))
# 打印ndarray对象a
print(a)
```
输出可能如下:
```python
[[2.67276450e+185 1.69506143e+190 1.75184137e+190]
[9.48819320e+077 1.63730399e-306 0.00000000e+000]]
```