numpy的使用
array本身属性
- shape:返回一个元组,表示array的维度
- ndim:array是几维的
- size:array所有元素数目
- dtype:array中元素类型(与List不同的是,array中所有元素必须都是相同类型)
array的创建
import numpy as np
# 直接根据python的List生成array
x = np.array([1,2,3,4,5,6])
x = np.array([
[1,2,3],
[4,5,6],
])
# 使用arange创建数字序列
x = np.arange(10) # [0,10)的整数
x = np.arange(2,10,2) # [2,10)的整数,步长为2
# 使用特殊的方式
x = np.ones(shape,dtype=None,order='C') # 创建全是1的数组,shape是整数或者元组,表示数组的形状,后面两个参数可以不写
x = np.ones_like(a,dtype=float,order='C') # 创建形状和a数组一样的数字,所有元素全部设为1,后面两个参数可以不写
# np.zeros与np.ones用法类似
x = np.empty(shape,dtype=float,order='C') # 元素的值未初始化,不能随意使用
x = np.empty_like(a,dtype=float,order='C') # 类似
x = np.full(shape,fill_value,dtype=None,order='C') # fill_value是用来初始化的值,shape指定形状,全部初始化为fill_value
# full_like类似
x = np.random.randn() # 返回一个数字
x = np.random.randn(3,2) # 生成一个三行两列
x = np.random.randint(1,100,10) # 生成1到100的数字,一共要10个
array的操作
调整形状
x = np.arange(12)
x = x.reshape(2,6) # 调整后的整体元素数量要与之前相同
查看形状
x = np.arange(12).reshape(2,6)
x.shape # 返回一个元组(2,6)
按元素操作
x = np.arange(12).reshape(2,6)
x+1 # 把数组x中每个元素+1
x*3 # 把数组中每个元素×3
np.sin(x) # 计算每个元素的sin值
np.exp(x) # 计算每个元素的e的x次方
y = np.random.randn(2,6)
x + y # 按元素+
x - y # 按元素-
索引、切片
一般索引
# 类似python原生切片方法
x[index] # 取指定下标
x[start:end] # 前闭后开
x[2:-1] # 从第3个到最后一个
x[2:] # 第3个到最后
x[:-1] # 从前到最后一个
# numpy特有的切片方法
x[0,1,2] # 直接用逗号
x[0,1] = 123 # 给切片赋值,影响原来的数组
神奇索引
x = np.array([
7,3,6,3,6,8,43,1,45
])
x[[3,4,7]]
# 将会根据索引中提供的下标列表,查找相应下标对应的元素数值,然后按照索引的格式返回数据,返回的结果是array([6,3,43])
indexs = np.array([[0,2],[1,3]])
x[indexs]
# 返回的结果是array([[7,6],[3,3]])
x = np.array([
[1,2,3,4,5],
[6,7,8,9,10],
[11,12,13,14,15]
])
x[[0,2]] # 取前两行
x[:,[0,2] # 取所有行的前两列
x[[0,2],[0,2]] # 取0行0列的和1行1列的组成一个一维数组
布尔索引
x = np.arange(12)
x[x>5] # 获得大于5的元素列表
x[x>5]=1 # 二值化
x[x<=5]=0
x = np.aragne(12).reshape(3,4)
x[x>5] # 不考虑维度,仅针对每个元素
# 条件组合 每个条件都必须加小括号
x = np.arange(10)
condition = (x%2==0) | x>7
x[condition]