python之numpy

1.简介

Numpy是 Python 语言的一个扩展程序库,支持大量的维度数组与矩阵运算,此外也针对数组运算提供大量的数学函数库。

2.创建数组以及数组的dtype属性

import numpy as np
# 通过numpy创建数组,数组数据类型是numpy.ndarray;其中b、c效果一样
a=np.array([1,2,3])
b=np.array(range(10))
c=np.arange(10)
print(a,b,c)          ------------->[1 2 3] [0 1 2 3 4 5 6 7 8 9] [0 1 2 3 4 5 6 7 8 9]
print(type(a),type(b),type(c))-----><class 'numpy.ndarray'> <class 'numpy.ndarray'> <class 'numpy.ndarray'>
b1=np.array(range(4,10,2))
c1=np.arange(4,10,2)
print(b1,c1)----------------------->[4 6 8] [4 6 8]
print(type(b1),type(c1))-----------><class 'numpy.ndarray'> <class 'numpy.ndarray'>
# 数组的属性dtype是当前数组里存放的数据的类型
print(b.dtype)--------------------->int32
# 指定数组的存放的数据的数据类型
d=np.array(range(1,4),dtype="int64")
print(d)--------------------------->[1 2 3]
print(d.dtype)--------------------->int64
# 指定为bool类型
bo=np.array([1,0,1,1,0,1],dtype="bool")
print(bo)--------------------------->[ True False  True  True False  True]
print(bo.dtype)--------------------->bool
#修改数据类型赋值给新的,旧的不变
newbo=bo.astype("int")
print(newbo,bo)--------------------->[1 0 1 1 0 1] [ True False  True  True False  True]
print(newbo.dtype,bo.dtype)--------->int32 bool

3.数组形状

import numpy
'''查看数组形状'''
a=numpy.array(range(12))
print(a)------------------------------------------>[ 0  1  2  3  4  5  6  7  8  9 10 11]
print(a.shape)------------------------------------>(12,)
a2=numpy.array([[1,2,3],[4,5,6]])
print(a2)----------------------------------------->[[1 2 3]
 													[4 5 6]]
print(a2.shape)----------------------------------->(2, 3)
'''修改数组形状'''
a3=numpy.array(range(10))
print(a3)----------------------------------------->[0 1 2 3 4 5 6 7 8 9]
print(a3.shape)----------------------------------->(10,)
a4=a3.reshape((5,2))#修改数组形状后赋值给a4,但a3没有改变
print(a4)----------------------------------------->[[0 1]
													[2 3]
													[4 5]
													[6 7]
													[8 9]]
print(a4.shape)----------------------------------->(5, 2)
'''转成一维数组'''
b=a4.flatten()#转成一维数组
print(b)------------------------------------------>[0 1 2 3 4 5 6 7 8 9]
print(b.shape)------------------------------------>(10,)

4.数组的计算

4.1 数组和数的计算

#数组计算
import numpy
a=numpy.array(range(
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值