美文网首页
Python—Numpy学习笔记(四)随机数生成以及矩阵的运算2

Python—Numpy学习笔记(四)随机数生成以及矩阵的运算2

作者: Yao_0 | 来源:发表于2017-07-15 21:00 被阅读0次

注:本系类笔记采用的是Python3.5X版本,编程环境为Windows64位下的Anaconda
所有代码部分均为连续的,“结果”为在jupyter分步运行结果

代码部分:

import numpy as np
sample1 = np.random.random((3,2))#生成3行2列从0到1的随机数
print(sample1)

结果:
[[ 0.42548654 0.60831272]
[ 0.48034909 0.70289579]
[ 0.96871932 0.33469266]]

sample2 = np.random.normal(size=(3,2))#生成3行2列符合标准正态分布的随机数
print(sample2)

结果:
[[ 0.82645622 -0.63300866]
[ 0.18604463 -0.30988056]
[-1.50301955 -0.51466896]]

sample3 = np.random.randint(0,10,size=(3,2))#生成3行2列从0到10的随机整数
print(sample3)

结果:
[[2 4]
[3 1]
[0 3]]

————————————————————————————————————
以下是对随机数的计算

np.sum(sample1)#求和

结果:
3.5204561139867017

np.min(sample1)#求最小值

结果:
0.33469265548836047

np.max(sample1)#求最大值

结果:
0.96871931960307933

np.sum(sample1,axis=0)#对列求和

结果:
array([ 1.87455495, 1.64590117])

np.sum(sample1,axis=1)#对行求和

结果:
array([ 1.03379926, 1.18324488, 1.30341198])

print(sample1)

结果:
[[ 0.42548654 0.60831272]
[ 0.48034909 0.70289579]
[ 0.96871932 0.33469266]]

np.argmin(sample1)#求最小值的索引

结果:
5
原因:sample1索引是按如下顺序排列的
[[0 1]
[2 3]
[4 5]]

np.argmax(sample1)#求最大值的索引

结果:
4

print(np.mean(sample1))#求平均值 (方法一)
print(sample1.mean())#求平均值(方法二)

结果:
0.586742685664
0.586742685664

np.median(sample1)#求中位数
#如果是单数,则求中间的值
#如果是双数,则求中间两个值得平均值

结果:
0.5443309058371042

np.sqrt(sample1)#开方

结果:
array([[ 0.65229329, 0.77994405],
[ 0.69307221, 0.8383888 ],
[ 0.9842354 , 0.57852628]])

sample4 = np.random.randint(0,10,size=(1,10))
print(sample4)

结果:
[[9 2 3 0 2 8 1 3 2 8]]

np.sort(sample4)#排序

结果:
array([[0, 1, 2, 2, 2, 3, 3, 8, 8, 9]])

np.sort(sample1)#对多维矩阵的排序

结果:
array([[ 0.42548654, 0.60831272],
[ 0.48034909, 0.70289579],
[ 0.33469266, 0.96871932]])

np.clip(sample4,2,7)#小于2就变成2,大于7就变为7

结果:
array([[7, 2, 3, 2, 2, 7, 2, 3, 2, 7]])

相关文章

网友评论

      本文标题:Python—Numpy学习笔记(四)随机数生成以及矩阵的运算2

      本文链接:https://www.haomeiwen.com/subject/aflzhxtx.html