数值运算-numpy基本操作

本文详细介绍了numpy库在Python中的使用,包括生成数组、数据类型操作、数组形状调整、数组计算、读取本地数据和索引、nan与inf处理、结合matplotlib作图以及数组的拼接和行列交换等核心功能。
摘要由CSDN通过智能技术生成

生成数组

生成正数

  1. 直接生成
    t1 = np.array([1,2,3])
  2. range生成
    t2 = np.array(range(10))
  3. arange生成(numpy独有)
  • 使用方法类似range
    t3 = np.arange(4,10,2)

生成小数

t7= np.array([random.random() for i in range(10)])  
print(t7)  
print(t7.dtype)  
  
t8= np.round(t7,2) #取近似两位 
print(t8)

---------------------
[0.10012212 0.95524231 0.25023686 0.65104295 0.29307086 0.18376068
 0.34930801 0.92896144 0.79899637 0.79465704]
float64

[0.1  0.96 0.25 0.65 0.29 0.18 0.35 0.93 0.8  0.79]

数据类型操作

查看数据类型

t3 = np.arange(4,10,2)
print(t3.dtype)
-------------------------
int64

改变数组存储方式

  • 节省内存空间
t4 = np.array(range(1,4),dtype ="i1")  
print(t4.dtype)
---------------
int8

t5 = np.array([1,1,0,1,0,0],dtype=bool)  
print(t5)  
print(t5.dtype)
---------------
[ True  True False  True False False]
bool

t6= t5.astype("int8")
print(t6)
print(t6.dtype)
----------------
[1 1 0 1 0 0]
int8


数组的形状

查看形状

  • 可以理解为:数组的维度
t8= np.array([[1,2,3],[4,5,6]])  
print(t8.shape)
------------------------
(2, 3)    #二维,两行三列


t8= np.array([[[1,2,3],[4,5,6]],[[3,4,5],[6,7,8]]])  
print(t8.shape)
------------------------
(2, 2, 3)  #,三维两块两行三列

修改形状

  1. 升维
t3 = np.arange(12)  
t4 = t3.reshape((3,4)) # 变为二维

print(t3.shape)  
print(t4.shape)
------------------------
(12,)
(3, 4)

    <
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值