python数组自增_Python连载|Numpy系列(上)

原标题:Python连载|Numpy系列(上)

Numpy是使用Python进行科学计算的基础软件包,它提供了高效的大数据数组处理能力和许多线性计算的内置函数,可见其重要性不言而喻。那么本期先给大家介绍一下Numpy的利器--数组及数组运算。

1. 数组

ndarray是一系列同类型数据的集合,以 0 下标为开始进行集合中元素的索引。

ndarray 对象是用于存放同类型元素的多维数组。ndarray 中的每个元素在内存中都有相同存储大小的区域。

1.1 创建数组

最简单的方式是使用array函数来创建数组

data1=[ 6, 7.5, 8, 0, 1]

arr1=np.array(data1)

arr1 # array([6. , 7.5, 8. , 0. , 1. ])

此外,还可以通过以下方法来创建数组

从已有数组创建:numpy.asarray(a, dtype = None, order = None)

数值接近于0的数组:numpy.empty(shape, dtype = float, order = 'C')

全0数组:numpy.zeros(shape, dtype = float, order = 'C')

全1数组:numpy.ones(shape, dtype = None, order = 'C')

数值范围数组:numpy.arange(start, stop, step, dtype)

等差数列:numpy.linspace(start,stop,num,dtype)

对角数组:numpy.eye(N, M=None, k=0, dtype=, order='C')

其中shape表示数组形状,dtype为数据类型,order中的C和F分别代表行优先和列优先

具体的创建用例如下:

print( "np.zeros((2,2)):n", np.zeros(( 2, 2)))

print( "np.ones((2,2)):n", np.ones(( 2, 2)))

print( "np.eye((2)):n", np.eye(( 2)))

print( "np.random.random((2,2)):n", np.random.random(( 2, 2)))

print( "np.linspace(1,10,10):n",np.linspace( 1, 10, 10))

输出结果

np.zeros(( 2, 2)):

[[ 0.0.]

[ 0.0.]]

np.ones(( 2, 2)):

[[ 1.1.]

[ 1.1.]]

np.eye(( 2)):

[[ 1.0.]

[ 0.1.]]

np.random.random(( 2, 2)):

[[ 0.572234090.08745789]

[ 0.540976320.87183112]]

np.linspace( 1, 10, 10):

[ 1.2.3.4.5.6.7.8.9.10.]

1.2 数组对象常用方法

ndarray对象常用方法有以下几种

方法

描述

ndim

秩,即轴的数量或维度的数量

shape

数组的维度,对于矩阵,n 行 m 列

size

数组元素的总个数

dtype

ndarray 对象的元素类型

tolist

narray对象转化为list

newaxis

给原数组增加一个维度

使用这些方法,可以快速的获取数组的一些信息

x=np.array([ 1, 2, 3, 4, 5])

# 秩

print( "x ndim: ", x.ndim)

# 维度

print( "x shape:", x.shape)

# 数组元素的总个数

print( "x size: ", x.size)

# ndarray 对象的元素类型

print( "x dtype: ", x.dtype)

# narray对象转化为list

print( "x tolist:",x.tolist)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值