数据分析之NumPy(三)基本操作

生成数组的方法

生成0和1的数组

  • ones(shape[, dtype, order]) 全为0的数组
  • zeros(shape[, dtype, order]) 全为0的数组
  • empty(shape[, dtype, order]) 不初始化,里面的值不能使用
  • full(shape, fill_value[, dtype, order]) 全为指定值
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

从现有数组生成

从现有数组生成数组的api有:

  • array(object[, dtype, copy, order, subok, ndmin])
  • asarray(a[, dtype, order])
  • copy(a[, order])
  • asanyarray(a[, dtype, order]) ascontiguousarray(a[, dtype])
  • asmatrix(data[, dtype])
a = np.array([[1,2,3],[4,5,6]])
# 从现有的数组当中创建
a1 = np.array(a)
# 相当于索引的形式,并没有真正的创建一个新的
a2 = np.asarray(a)

关于array和asarray的不同
在这里插入图片描述
在这里插入图片描述

生成固定范围的数组

生成固定范围的数组的api有:

numpy.arange

numpy 包中的使用 arange 函数创建数值范围并返回 ndarray 对象,函数格式如下:

numpy.arange(start, stop, step, dtype)

根据 start 与 stop 指定的范围以及 step 设定的步长,生成一个 ndarray。

numpy.linspace

numpy.linspace 函数用于创建一个一维数组,数组是一个等差数列构成的,格式如下:

np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)

numpy.logspace

numpy.logspace 函数用于创建一个于等比数列。格式如下:

np.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)

base 参数意思是取对数的时候 log 的下标。

例如:

np.linspace (start, stop, num, endpoint, retstep, dtype)生成等间隔的序列

start 序列的起始值
stop 序列的终止值,
如果endpoint为true,该值包含于序列中
num 要生成的等间隔样例数量,默认为50
endpoint 序列中是否包含stop值,默认为ture
retstep 如果为true,返回样例,
以及连续数字之间的步长
dtype 输出ndarray的数据类型

在这里插入图片描述
在这里插入图片描述

生成随机数组

np.random模块

numpy中利用random类获取随机数

numpy.random.random() 生成随机浮点数

API: random (size)

size参数默认为零,也可以传入[2,3]生成一个2行3列的数组,默认为生成一个随机的浮点数,范围是在0.0~1.0之间,也可以通过参数size设置返回数据的size;

numpy.random.randint() 生成随机整数

API: randint(low, high=None, size=None, dtype=’l’)

numpy.random.randint()随机生一个整数int类型,可以指定这个整数的范围

numpy.random. uniform () 生成均匀分布随机数

API: uniform (low=0.0, high=1.0, size=None)

numpy.random. uniform ()从一个均匀分布[low,high)中随机采样,注意定义域是左闭右开,即包含low,不包含high

numpy.random.normal()  高斯分布随机数(正态分布)

API: normal(loc=0.0, scale=1.0, size=None)

loc:均值,scale:标准差,size:抽取样本的size

numpy.random.randn() 标准正态分布随机数

API: numpy.random.randn(d0, d1, …, dn)

从标准正态分布中返回一个(d0d1 …* dn)维样本值

numpy.random.rand() 生成[0, 1)间随机数

API: numpy.random.rand(d0, d1, …, dn)

生成一个(d0d1 …* dn)维位于[0, 1)中随机样本

举例:
生成随机浮点数
在这里插入图片描述
生成随机整数
在这里插入图片描述
生成均匀分布随机数
在这里插入图片描述
生成高斯分布随机数(正态分布)
在这里插入图片描述
生成标准正态分布随机数
在这里插入图片描述
生成[0, 1)间随机数
在这里插入图片描述
生成均匀分布api简介

np.random.rand(d0, d1, ..., dn)
返回[0.0,1.0)内的一组均匀分布的数。

np.random.uniform(low=0.0, high=1.0, size=None)
功能:从一个均匀分布[low,high)中随机采样,注意定义域是左闭右开,即包含low,不包含high.
参数介绍:

  • low: 采样下界,float类型,默认值为0;
  • high: 采样上界,float类型,默认值为1;
  • size: 输出样本数目,为int或元组(tuple)类型,例如,size=(m,n,k), 则输出mnk个样本,缺省时输出1个值。
  • 返回值:ndarray类型,其形状和参数size中描述一致。

np.random.randint(low, high=None, size=None, dtype='l')
从一个均匀分布中随机采样,生成一个整数或N维整数数组,取数范围:若high不为None时,取[low,high)之间随机整数,否则取值[0,low)之间随机整数。

# 生成均匀分布的随机数
x1 = np.random.uniform(-1, 1, 100000000)
x1

返回结果:

array([ 0.22411206,  0.31414671,  0.85655613, ..., -0.92972446,
0.95985223,  0.23197723])

画图看分布状况:

import matplotlib.pyplot as plt

# 生成均匀分布的随机数
x1 = np.random.uniform(-1, 1, 100000000)

# 画图看分布状况
# 1)创建画布
plt.figure(figsize=(10, 10), dpi=100)

# 2)绘制直方图
plt.hist(x1, 1000)

# 3)显示图像
plt.show()

在这里插入图片描述
生成正态分布api简介

np.random.randn(d0, d1, …, dn)

功能:从标准正态分布中返回一个或多个样本值

np.random.normal(loc=0.0, scale=1.0, size=None)

  • loc:float
    ​ 此概率分布的均值(对应着整个分布的中心centre)
  • scale:float
    ​ 此概率分布的标准差(对应于分布的宽度,scale越大越矮胖,scale越小,越瘦高)
  • size:int or tuple of ints
    ​ 输出的shape,默认为None,只输出一个值

onp.random.standard_normal(size=None)

返回指定形状的标准正态分布的数组。
在这里插入图片描述

补充:正态分布(理解)
1 什么是正态分布
正态分布是一种概率分布。正态分布是具有两个参数μσ的连续型随机变量的分布,第一参数μ是服从正态分布的随机变量的均值第二个参数σ是此随机变量的方差所以正态分布记作N(μ,σ )
在这里插入图片描述
2 正态分布的应用
生活、生产与科学实验中很多随机变量的概率分布都可以近似地用正态分布来描述。
3 正态分布特点
μ决定了其位置,其标准差σ决定了分布的幅度。当μ = 0,σ = 1时的正态分布是标准正态分布。
在这里插入图片描述
标准差如何来?
方差
在概率论和统计学中衡量一组数据离散程度的度量
在这里插入图片描述
其中M为平均值,n为数据总个数,S为标准差,S^2可以理解一个整体为方差
在这里插入图片描述
标准差与方差的意义
可以理解成数据的一个离散程度的衡量
在这里插入图片描述
x2 = np.random.normal(1.75, 1, 100000000)
返回结果:array([2.90646763, 1.46737886, 2.21799024, ..., 1.56047411, 1.87969135,0.9028096 ])

# 生成均匀分布的随机数
x2 = np.random.normal(1.75, 1, 100000000)

# 画图看分布状况
# 1)创建画布
plt.figure(figsize=(20, 10), dpi=100)

# 2)绘制直方图
plt.hist(x2, 1000)

# 3)显示图像
plt.show()

在这里插入图片描述
例如:我们可以模拟生成一组股票的涨跌幅的数据

案例:随机生成8只股票2周的交易日涨幅数据
8只股票,两周(10天)的涨跌幅数据,如何获取?

  • 两周的交易日数量为:2 X 5 =10
  • 随机生成涨跌幅在某个正态分布内,比如均值0,方差1

股票涨跌幅数据的创建
创建符合正态分布的8只股票10天的涨跌幅数据

import numpy as np
stock_change = np.random.normal(0,1,[8,10])
stock_change

在这里插入图片描述

数组的索引、切片

  • 获取第一个股票的前3个交易日的涨跌幅数据
# 二维的数组,两个维度 
stock_change[0, 0:3]

返回结果:

array([ 0.55891904, -0.13130443,  0.24597672])

一维、二维、三维的数组如何索引?

# 三维,一维
a1 = np.array([ [[1,2,3],[4,5,6]], [[12,3,34],[5,6,7]]])
a1

返回结果
在这里插入图片描述

# 索引、切片
a1[0, 0, 1]   # 输出: 2

在这里插入图片描述

形状修改

需求:让刚才的股票行、日期列反过来,变成日期行,股票列

  • ndarray.reshape(shape[, order]) Returns an array containing the same data with a new shape.
#在转换形状的时候,一定要注意数组的元素匹配
stock_change.reshape([10, 8]) # 只是将形状进行了修改,但并没有将行列进行转换
stock_change.reshape([-1,20])  # 数组的形状被修改为: (4, 20), -1: 表示通过待计算

在这里插入图片描述

  • ndarray.T 数组的转置
#将数组的行、列进行互换
stock_change.shape
(8, 10)
stock_change.T.shape
(10, 8)
  • ndarray.resize(new_shape[, refcheck]) Change shape and size of array in-place.
stock_change.resize([10, 8])

在这里插入图片描述

类型修改

  • ndarray.astype(type)
stock_change.astype(np.int32)

在这里插入图片描述

  • ndarray.tostring([order])或者ndarray.tobytes([order]) Construct Python bytes containing the raw data bytes in the array.
#转换成bytes
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[12, 3, 34], [5, 6, 7]]])
arr.tostring()

在这里插入图片描述

bug:如果遇到
IOPub data rate exceeded. The notebook server will temporarily stop sending output to the client in order to avoid crashing it. To change this limit, set the config variable --NotebookApp.iopub_data_rate_limit.
这个问题是在jupyer当中对输出的字节数有限制,需要去修改配置文件
创建配置文件
jupyter notebook --generate-config vi ~/.jupyter/jupyter_notebook_config.py
取消注释,多增加
## (bytes/sec) Maximum rate at which messages can be sent on iopub before they #are limited. c.NotebookApp.iopub_data_rate_limit = 10000000
但是不建议这样去修改,jupyter输出太大会崩溃

数组的去重

  • np.unique(a)
    在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_42642945/article/details/88344928