数据分析Numpy基础
1、通过ndarray的astype方法显式的转换其dtype
import numpy as np
arr = np.array([1,2,3])
arr.dtype
float_arr = arr.astype(np.float64)
float_arr.dtype
2、基本的索引和切片
- 数组切片
数组切片和列表的最大区别在于,数组切片是原始数据的视图,意味着数据不会被赋值,视图上的任何修改都会直接反映到源数组上
arr = np.arange(4)
arr_slice = arr[1:3]
arr_slice[:] = 333
-
二维数组索引方式
axis = 0,取列; axis = 1,取行
-
切片索引
arr2d = np.array([[1,2,3],[4,5,6],[7,8,9]])
arr2d[:2,1:]
- 布尔型索引
data = np.random.randn(2,5)
data[data<0]=0
注:python关键字and和or在布尔型数组中无效
- 花式索引
arr = np.arange(32).reshape((8,4))
arr[[1,5,7,2],[0,3,1,2]]
注:花式索引和切片不一样,它总是将数据复制到新数组中。
- 部分numpy.random函数
范例:随机漫步
- np.where()
当数组是二维数组时,满足条件的数组值返回的是值的位置索引,因此会有两组索引数组来表示值的位置,返回的第一个array表示行坐标,第二个array表示纵坐标,两者一一对应
b = np.arange(4*5).reshape(4,5)
b
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
np.where(b>15)
(array([3, 3, 3, 3], dtype=int64), array([1, 2, 3, 4], dtype=int64))
- 一次模拟多次随机漫步
nwalks = 5000
nsteps = 1000
draws = np.random.randint(0,2,size = (nwalks, nsteps)) #范围从低(包括)到高(不包括)
steps = np.where(draws>0, 1, -1)
walks = steps.cumsum(1)
#cumsum(), axis=0,代表以行方式扫描,第一次扫描第一行,第二次扫描第二行,以此类推。
#第一行扫描时,没有前几行可累加,所以数值不变。扫描到第二行,累加前几行,以此类推。
walks
array([[ 1, 2, 1, ..., -6, -7, -8],
[ 1, 0, 1, ..., 10, 9, 10],
[ -1, -2, -3, ..., -22, -23, -22],
...,
[ -1, 0, 1, ..., 24, 23, 24],
[ 1, 2, 3, ..., -42, -43, -44],
[ -1, -2, -1, ..., 14, 13, 14]], dtype=int32)