# 创建 Numpy 数组的不同方式

Numpy库的核心是数组对象或ndarray对象（n维数组）。你将使用Numpy数组执行逻辑，统计和傅里叶变换等运算。作为使用Numpy的一部分，你要做的第一件事就是创建Numpy数组。本指南的主要目的是帮助数据科学爱好者了解可用于创建Numpy数组的不同方式。

1. 使用Numpy内部功能函数
2. 从列表等其他Python的结构进行转换
3. 使用特殊的库函数

## 使用Numpy内部功能函数

Numpy具有用于创建数组的内置函数。 我们将在本指南中介绍其中一些内容。

### 创建一个一维的数组

``````import Numpy as np
array = np.arange(20)
array
``````

``````array([0,  1,  2,  3,  4,
5,  6,  7,  8,  9,
10, 11, 12, 13, 14,
15, 16, 17, 18, 19])
``````

``````array.shape
``````

``````(20,)
``````

``````array[3]
``````

``````3
``````

Numpy的数组是可变的，这意味着你可以在初始化数组后更改数组中元素的值。 使用print函数查看数组的内容。

``````array[3] = 100
print(array)
``````

``````[  0   1   2 100
4   5   6   7
8   9  10  11
12  13  14  15
16  17  18  19]
``````

``````array[3] ='Numpy'
``````

``````ValueError: invalid literal for int() with base 10: 'Numpy'
``````

### 创建一个二维数组

``````array = np.arange(20).reshape(4,5)
array
``````

``````array([[ 0,  1,  2,  3,  4],
[ 5,  6,  7,  8,  9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
``````

``````(4, 5)
``````

``````array[3][4]
``````

``````19
``````

### 创建三维数组及更多维度

``````array = np.arange(27).reshape(3,3,3)
array
``````

``````array([[[ 0,  1,  2],
[ 3,  4,  5],
[ 6,  7,  8]],

[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],

[[18, 19, 20],
[21, 22, 23],
[24, 25, 26]]])
``````

``````array.shape
``````

``````(3, 3, 3)
``````

``````np.arange(10, 35, 3)
``````

``````array([10, 13, 16, 19, 22, 25, 28, 31, 34])
``````

### 使用其他Numpy函数

``````np.zeros((2,4))
``````

``````array([[0., 0., 0., 0.],
[0., 0., 0., 0.]])
``````

``````np.ones((3,4))
``````

``````array([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]])
``````

`empty`函数创建一个数组。它的初始内容是随机的，取决于内存的状态。

``````np.empty((2,3))
``````

``````array([[0.65670626, 0.52097334, 0.99831087],
[0.07280136, 0.4416958 , 0.06185705]])
``````

`full`函数创建一个填充给定值的n * n数组。

``````np.full((2,2), 3)
``````

``````array([[3, 3],
[3, 3]])
``````

`eye`函数可以创建一个n * n矩阵，对角线为1s，其他为0。

``````np.eye(3,3)
``````

``````array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
``````

``````np.linspace(0, 10, num=4)
``````

``````array([ 0., 3.33333333, 6.66666667, 10.])
``````

## 从Python列表转换

``````array = np.array([4,5,6])
array
``````

``````array([4, 5, 6])
``````

``````list = [4,5,6]
list
``````

``````[4, 5, 6]
``````
``````array = np.array(list)
array
``````

``````array([4, 5, 6])
``````

``````type(list)
``````

list

``````type(array)
``````

Numpy.ndarray

``````array = np.array([(1,2,3), (4,5,6)])
array
``````

``````array([[1, 2, 3],
[4, 5, 6]])
``````
``````array.shape
``````

``````(2, 3)
``````

## 使用特殊的库函数

``````np.random.random((2,2))
``````

``````array([[0.1632794 , 0.34567049],
[0.03463241, 0.70687903]])
``````