Python数据分析实战【第三章】1.5- Numpy随机数【python】

【课程1.5】 Numpy随机数

numpy.random包含多种概率分布的随机样本,是数据分析辅助的重点工具之一

随机数生成

samples = np.random.normal(size=(4,4))
print(samples)
# 生成一个标准正太分布的4*4样本值
-----------------------------------------------------------------------
[[ 0.17875618 -1.19367146 -1.29127688  1.11541622]
 [ 1.48126355 -0.81119863 -0.94187702 -0.13203948]
 [ 0.11418808 -2.34415548  0.17391121  1.4822019 ]
 [ 0.46157021  0.43227682  0.58489093  0.74553395]]

2.numpy.random.rand(d0, d1, …, dn):生成一个[0,1)之间的随机浮点数或N维浮点数组 —— 均匀分布

import matplotlib.pyplot as plt  # 导入matplotlib模块,用于图表辅助分析
% matplotlib inline 
# 魔法函数,每次运行自动生成图表

a = np.random.rand()
print(a,type(a))  # 生成一个随机浮点数

b = np.random.rand(4)
print(b,type(b))  # 生成形状为4的一维数组

c = np.random.rand(2,3)
print(c,type(c))  # 生成形状为2*3的二维数组,注意这里不是((2,3))

samples1 = np.random.rand(1000)
samples2 = np.random.rand(1000)
plt.scatter(samples1,samples2)
# 生成1000个均匀分布的样本值
----------------------------------------------------------------------
0.3671245126484347 <class 'float'>
[ 0.95365841  0.45627035  0.71528562  0.98488116] <class 'numpy.ndarray'>
[[ 0.82284657  0.95853197  0.87376954]
 [ 0.53341526  0.17313861  0.18831533]] <class 'numpy.ndarray'>

在这里插入图片描述

3.numpy.random.randn(d0, d1, …, dn):生成一个浮点数或N维浮点数组 —— 正态分布

samples1 = np.random.randn(1000)
samples2 = np.random.randn(1000)
plt.scatter(samples1,samples2)
# randn和rand的参数用法一样
# 生成1000个正太的样本值
-----------------------------------------------------------------------

在这里插入图片描述

4.numpy.random.randint(low, high=None, size=None, dtype=‘l’):生成一个整数或N维整数数组

# 若high不为None时,取[low,high)之间随机整数,否则取值[0,low)之间随机整数,且high必须大于low 
# dtype参数:只能是int类型  

print(np.random.randint(2))
# low=2:生成1个[0,2)之间随机整数  

print(np.random.randint(2,size=5))
# low=2,size=5 :生成5个[0,2)之间随机整数

print(np.random.randint(2,6,size=5))
# low=2,high=6,size=5:生成5个[2,6)之间随机整数  

print(np.random.randint(2,size=(2,3)))
# low=2,size=(2,3):生成一个2x3整数数组,取数范围:[0,2)随机整数 

print(np.random.randint(2,6,(2,3)))
# low=2,high=6,size=(2,3):生成一个2*3整数数组,取值范围:[2,6)随机整数  
-----------------------------------------------------------------------
1
[0 0 0 1 1]
[3 5 5 2 2]
[[1 1 1]
 [0 1 1]]
[[4 5 3]
 [2 3 4]]

作业1:请按照要求创建数组ar,再将ar[:2,:2]的值改为[0,1)的随机数
在这里插入图片描述

ar = np.arange(25, dtype = np.float32).reshape(5,5)
print(ar, '\n-------')
ar[:2,:2] = np.random.rand(2,2)
print('结果为:\n',ar, '\n-------')

作业2: 创建2个包含10个元素的正太分布一维数组

在这里插入图片描述

ar1 = np.random.normal(size = (2,5))
ar2 = np.random.normal(size = (2,5))
print(ar1, '\n-------')
print(ar2, '\n-------')
print('结果为:\n',np.vstack((ar1,ar2)))
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值