课程大纲 第 77 课,共 250 课 · 数据基础:numpy 与 pandas
数据基础:numpy 与 pandas

创建数组与索引

创建数组有好几种方式。最常见的是:

import numpy as np
a = np.array([1, 2, 3])      # from a list
b = np.arange(0, 10, 2)      # like range: [0 2 4 6 8]
z = np.zeros(4)              # [0. 0. 0. 0.]
o = np.ones((2, 3))          # a 2x3 grid of ones

每个数组都有一个 dtype(元素的类型)和一个 shape(它在每个维度上的大小):

a = np.array([1, 2, 3])
print(a.dtype)   # int32 or int64 depending on the platform (int32 in this browser)
print(a.shape)   # (3,)   one dimension, length 3

grid = np.array([[1, 2, 3], [4, 5, 6]])
print(grid.shape)  # (2, 3)   2 rows, 3 columns

索引和切片的用法和列表一样,从 0 开始:

a = np.array([10, 20, 30, 40, 50])
print(a[0])     # 10
print(a[-1])    # 50
print(a[1:4])   # [20 30 40]   start included, stop excluded

对于二维数组,用 grid[row, col] 索引:

print(grid[0, 2])   # 3  (row 0, column 2)
print(grid[1])      # [4 5 6]  (the whole second row)
轮到你了

用 numpy 建立 steps = np.arange(0, 10, 2)(0..8 的偶数)。把它的形状存进 shp。然后把中间三个值(索引 1、2、3)切片到 mid。

发现这节课有问题?报告它 · 就这节课提问

这个练习即将开放

完成它前面的那一课,这一课就会解锁。整门课程免费,无需账号,而且你现在就可以阅读这节课。