一、Numpy基础:创建数组

此页面是否是列表页或首页?未找到合适正文内容。

一、Numpy基础:创建数组

标签:table使用onelis数组元素浮点数浮点int填充

h2 { font-size: 24px; height: 35px; line-height: 35px !important; width: 95%; background-color: #169FE6; padding-left: 10px; color: white }
table { border: 1px solid #d3d3d3; background: #fefefe; width: 90% }
th,td { padding: 0.5% 1% 0.5% }
th { background: #e8eaeb }
td { border-top: 1px solid #e0e0e0; border-right: 1px solid #e0e0e0 }
tr:nth-child(2n+1) { background: #f6f6f6 }
td.first,th.first { text-align: left }
td.last { border-right: none }
td { background: -webkit-gradient(linear, 0% 0%, 0% 25%, from(#f9f9f9), to(#fefefe)) }
tr:nth-child(2n+1) td { background: -webkit-gradient(linear, 0% 0%, 0% 25%, from(#f1f1f1), to(#f6f6f6)) }
th { background: -webkit-gradient(linear, 0% 0%, 0% 20%, from(#ededed), to(#e8eaeb)) }
tr:first-child th.first { }
tr:first-child th.last { }
tr:last-child td.first { }
tr:last-child td.last { }
.syntaxhighlighter { width: 95% !important }

Numpy是Python的一个科学计算的库,提供了矩阵运算的功能,其一般与Scipy、matplotlib一起使用。其实,list已经提供了类似于矩阵的表示形式,不过numpy为我们提供了更多的函数。如果接触过matlab、scilab,那么numpy很好入手。

一、模块引用

import numpy as np

二、数组的创建

这里先看一下多维度数组的格式,下例是一个三维数组,以楼房的方式理解最直观。

[#数组一层[1, 3, 4, 6],#一层1单元[2, 5, 6, 7]#一层2单元],[#数组二层[1, 3, 4, 6],#二层1单元[2, 5, 6, 7]#二层2单元]

注意,数组元素必须放入[]或()之间

2.1普通创建
一维数组创建

np.array([1,2,3,4])
>>>array([1, 2, 3, 4])

多维数组创建

c=np.array([
[
[
[1,2],[3,4]#3维层(内部元素为思维)
],#2维层
[
[5,6],[7,8]
]
],#1维层
[
[
[9,10],[11,12]
],
[
[13,14],[15,16]#3维层(内部元素为思维)
]#2维层
]#1维层
])
print(c)
>>>
[[[[ 1 2]
[ 3 4]]
[[ 5 6]
[ 7 8]]]
[[[ 9 10]
[11 12]]
[[13 14]
[15 16]]]]?

2.1.1内置方法创建(arange创建)

arange的使用方法与python内置方法range相同,这里不再赘述,看程序

import numpy as np
a=np.arange(20)
b=np.arange(10,20)
c=np.arange(10,20,2)
d=np.arange(20,10,-1)
print(\”普通玩法:\”,a)
print(\”带起始点的玩法:\”,b)
print(\”带步长的玩法:\”,c)
print(\”倒着玩:\”,d)
>>>
普通玩法: [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
带起始点的玩法: [10 11 12 13 14 15 16 17 18 19]
带步长的玩法: [10 12 14 16 18]
倒着玩: [20 19 18 17 16 15 14 13 12 11]

2.1.2内置方法创建(random创建)

与random模块不同,这个random是numpy内置的方法,用法上是相同的,同样看程序

import numpy as np
a=np.random.random((2,2))#0~1的随机数
b=np.random.randn(2,2)#符合正态分布的随机数
c=np.random.randint(2,10,(2,2))#从2~10的随机整数
print(\”0~1的随机数:\”,a)
print(\”正态分布的随机数:\”,b)
print(\”从2~10的随机整数:\”,c)
>>>0~1的随机数: [[0.93614432 0.56444734]
[0.29267612 0.38625066]]
正态分布的随机数: [[-1.26606533 0.68466118]
[ 0.34377799 0.1318619 ]]
从2~10的随机整数: [[4 8]
[9 6]]

numpy.random下所有创建方式如下表所示:

方法名称
解析

rand(d0, d1, …, dn)
随机值。

randn(d0, d1, …, dn)
返回一个样本,具有标准正态分布。

randint(low[, high, size])
返回随机的整数,位于半开区间 [low, high)。

random_integers(low[, high, size])
返回随机的整数,位于闭区间 [low, high]。

random_sample([size])
返回随机的浮点数,在半开区间 [0.0, 1.0)。

choice(a[, size, replace, p])
生成一个随机样本,从一个给定的一维数组。

2.1.3内置方法创建(等差等比创建)

作者: 库巴司机

为您推荐

返回顶部