numpy学习笔记(代码)

import numpy as np
import random
#用numpy生成数组,t1,t2,t3
t1 = np.array([0, 1, 2, 3, 4])
print(t1,'\n')

t2 = np.array(range(5))
print(t2,'\n')

t3 = np.arange(5)
print(t3,'\n')

#用numpy生成的数组的类型为<class 'numpy.ndarray'>
print(type(t3),'\n')

#dtype显示的是数组元素的类型,
# 有int(8,16,32,64),float(16,32,64,128),uint(8,16,32,64),complex(64,128),bool这么多
print(t3.dtype,'\n')

"""创建不同类型的数组,用dtype参数"""
#float64类型
t4 = np.array(range(10), dtype=float)
print(t4)
print(t4.dtype,'\n')         #为float64是因为电脑为64位

#bool类型
t5 = np.array([1, 0, 0, 1, 0, 1], dtype=bool)
print(t5)
print(t5.dtype,'\n')

"""数据的类型转换,用astype("要转换的类型")方法"""

#bool转int8
t6 = t5.astype("int8")
print(t6, t6.dtype,'\n')

"""修改小数的位数,用roung方法"""
t7 = np.array([random.random() for i in range(10)])
print(t7, t7.dtype,'\n')
#取3位小数
t8 = np.round(t7,3)
print(t8, t8.dtype,'\n')

#不在numpy中的取小数,取3位
print(round(random.random(),3),'\n')


"""数组的形状"""
#查看数组的形状  .shape
#一维
d1 = np.array(range(12))
print(d1,d1.shape,'\n')
#二维
d2 = np.array([[1, 2, 3], [4, 5, 6]])
print(d2,d2.shape,'\n')

"""修改数组的形状 reshape()"""
l = np.array([0,1,2,3,4,5,6,7,8,9,10,11])
#二维
d3 = l.reshape(3, 4)
print(d3,d3.shape,'\n')
#三维
d4 = np.array(range(24)).reshape(2,3,4)
print(d4, d4.shape,'\n')
#4维
d5 = np.array(range(48)).reshape(2,2,3,4)
print(d5,d5.shape,'\n')

"""将多维数组展开,flatten()"""
#用reshape展开
d6 = d5.reshape(d5.shape[0]*d5.shape[1]*d5.shape[2]*d5.shape[3],)
print(d6, d6.shape,'\n')

d7 = d5.flatten()
print(d7, d7.shape,'\n')

"""数组与数字,数组与数组进行计算"""
a1 = np.array(range(12)).reshape(3,4)
print('数组与数字:\n',a1,'\n')
print(a1+5,'\n')
print(a1-5,'\n')
print(a1*5,'\n')
print(a1/5,'\n')

#数组与数组进行计算是,维度要基本一致,维度不一致时,有时可以计算,有时不可以
print('数组与数组:\n',a1+a1,'\n')
print(a1-a1,'\n')
print(a1*a1,'\n')
print(a1/a1,'\n')
"""数据的索引与切片"""
import numpy as np

t1 = np.array(range(24)).reshape((4, 6))
print(t1, '\n')
#取行
print(t1[1:], '\n')     #取1到最后一行
#取不连续的行
print(t1[[0, 2, 3]], '\n')

#取列
print(t1[:, 0], '\n')  #取第0列

print(t1[:, [2, 4, 5]], '\n') #取多列

#取多行多列
print(t1[[0,2,3],[1,4,5]], '\n')



"""numpy中数值的修改"""

#将数组中下于10的数字替换成3
print(t1, '\n')
print(t1[t1<10], '\n')  #打印出小于10的元素
t1[t1<10] = 3           #将小于10的数赋值为3
print(t1, '\n')

"""numpy中的三元运算符where"""
t2 = np.where(t1 < 10, 0, 20, '\n')  #将t1中小于10的替换成0,否则(大于等于10)替换成20
print(t2)

"""numpy中的裁剪clip"""
t3 = t1.clip(10,18)  #小于10的会被替换为10,大于18的会被替换成18
print(t3, '\n')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值