关于numpy的基本使用与练习题,相信会对你有所帮助

100道numpy题资源与答案链接在此

numpy数组的创建

np.arange()函数用来迭代生成整形变量,类似range函数
np.linspace(start,end,rownum)函数可以用来迭代生成浮点型变量,其中start和end是指开始和结束的数字,rownum是指从start到end的数据分为多少行
np.empty()生成随机浮点数矩阵
np.zeros()生成随机全零矩阵
np.ones()生成全1矩阵
np.pi生成圆周率
np.exp(1)生成自然对数

import numpy as np 
#利用np.array创建数组
#这样创建出来的数组是没有逗号进行分割的~
a=np.array([1,2],dtype=np.int)
print(a)
print(a.dtype)
#生成全0矩阵,给出shape
print( np.zeros(shape=(3,4),dtype=np.float32  ))
#生成全1矩阵,给出shape
print(np.ones(shape=(3,4),dtype=np.float32 ))

#生成全空矩阵(实际上其中的每个值都是无限接近0的),给出shape
print( np.empty(shape=(3,4),dtype=np.float32  ))
#有序数组
print( np.arange(start=0,stop=10,step=1))
#将[start,stop]范围划分为num个数,一般用于生成刻度ticks
#endpoint,是否包含有端点
print( np.linspace(start=0,stop=10,num=11,endpoint=False))
#np.fromfunction
#lambad 中的i和j可以看做是被指定的数组的维度
#也就是说数组中每一个(i,j)位置对应的数值由传入的function根据i和j去计算
print(np.fromfunction(lambda i ,j :(i+1)*(j+1),(9,9)))

在这里插入图片描述

numpy的基本运算

import numpy as np 
#随机产生一个size大小的矩阵
a=np.random.random(size=(2,4))
print(a)
#返回最小值的索引,arg参数缩写
#这里的索引值不加axis参数限定轴,默认按照拉伸成一维之后的索引
a=np.arange(10).reshape(2,5)
print(np.argmin(a))
print(np.argmax(a))
#求均值
print(np.mean(a))
#求均值
print(np.average(a))
#求中位数
print(np.median(a))
#cumsum求累加,不给axis按照一位数组进行累加
#返回数组的每一个位置pos的值为从[0,pos]的累加
print(np.cumsum(a))
#累差,从[1,]开始的 
print(np.diff(a))
#非零的位置
#返回a.ndim个数组,第i个数组代表a中的第i个维度的非零位置的i维度坐标
print(np.nonzero(a))
#矩阵的转置
print(a.T)
print(np.transpose(a))
#矩阵的截取,把矩阵内的值归一化到a_min和a_max内,相当于上下限(都为闭区间)
print(np.clip(a,a_min=1,a_max=3))
# 矩阵乘法,会把10广播成a的形状
y = np.multiply(a,10)
print(y)

在这里插入图片描述

numpy维度操作

import numpy as np

a=np.arange(10).reshape(2,5)

#reshape只改变数组的形状,不会改变数组的大小(元素个数)
print(a.reshape(5,2))
#resize会改变数组的形状和大小
#当新的形状大小比原来的大,就会用原始数组中的数据去填充
print(a.resize(5,5))

numpy的切片

import numpy as np
a=np.arange(10).reshape(5,2)
#迭代每一行
for row in a:
    print(row)
#迭代每一列
for column in a.T:
    print(column)
#迭代每一个
for v in a.flat:
    print(v)

在这里插入图片描述

numpy的分割

import numpy as np
a=np.arange(12).reshape(3,4)

numpy的基本概念

import numpy as np
demo=np.array([
    [
        [1,2,3]
    ],
    [
        [4,5,6]
    ],
    [
        [7,8,9]
    ]
])
#返回numpy数组的维度
print(demo.ndim)
#返回numpy数组的形状
print(demo.shape)
#返回numpy数组的个数
print(demo.size)
#数组中的每一个数字都平方,和维度无关
print(demo**2)
#把数组看做是一个自变量集合,每一个数字都作为自变量进行运算
print(np.exp(demo))
print(np.log(demo))
print(np.sqrt(demo))


#对应位置相乘有广播机制,没有验证
print(np.array([1,1])*np.array([2,3]))
#矩阵乘法,数组维度满足矩阵乘法的要求,第一个数组的列向量等于第二个数组的行向量
#特别注意这里面蕴含的广播机制
x=np.array([1,1])
y=np.array([[2],[3]])
print(x@y)
#点乘,和矩阵乘法一样
x=np.array([1,1])
y=np.array([[2],[3]])
print(x.dot(y))


#numpy 的flat 属性
for e in demo.flat:
    #按照行优先依次遍历数组
    #numpy.flat是一个迭代器
    print(e)

在这里插入图片描述

列表和数组区别

以list和tuple等数据结构表示数组
需要存储指针(因为数组可以存储任意类型的对象)
array模块
通过array函数创建数组
提供append,insert和read等方法
不支持多维数组
函数工具不够丰富
ndarray
多维数组
维度(dimensions)称为轴(axis)
轴的个数称为秩(rank)
基本属性
ndarray.ndim(秩)
ndarray.shape(维度)
ndarray.size(元素总个数)
ndarray.dtype(元素类型)
ndarray.itemsize(元素字节大小)
numpy通用函数ufunc(universal function):
通用函数是指能够对数组的每个元素都进行操作的函数

numpy中矢量化运算和广播思想

import numpy as np 
score=np.array([[1,2,3],[4,5,6]])
#keepdims 保持原有数组的维度
score_mean=score.mean(axis=1,keepdims=True)
score_mean

在这里插入图片描述

numpy中维度变化操作

import numpy  as  np
data=np.array([[1,2],[3,4]])
#flatten(),C 按照行优先展开
#F按照列优先展开
#展开后返回的是原始数组的副本

print(data)
print(data.flatten())
print(data)


#flat属性:返回1-D数组的迭代器
for i in data.flat:
    print(i)
    
#ravel()返回一维数组
print(data.ravel())
#np.squeeze(ndarray,axis)裁剪,如果不加axis参数,ndarray中所有维度为1的轴裁剪掉
#如果选定的axis的长不是1,报错
#如果没选定axis且ndarray内没有维度为1的维度,则报错
data2=np.ndarray([1,3,2,1])
print(np.squeeze(data2))

#特别注意,如果对于一个各个维度都为1的数组使用squeeze,则最后返回0-D数组
print(np.squeeze([[1,2,3,4]]))


'''
np.ndindex(shape):
返回大小为shape的矩阵的下标元组迭代器
如传入(2,3),
返回(2, 3)
(0, 0)
(0, 1)
(0, 2)
(1, 0)
(1, 1)
(1, 2)
'''
a=np.array([[1,2,3],[3,4,5]])
print(a.shape)
for i in np.ndindex(a.shape):
    print(i)

x = np.array([[[0], [1], [2]]])
print(x.shape)
y = np.squeeze(x,axis=-1)
print(y)

在这里插入图片描述

numpy中的fancy indexing(花哨索引)

'''
fancy indexing 索引
可以用np.take(a,indices,axis)对a中的indices部分进行切片截取,axis指定轴
如果indices是一个ndarray数组,那么这时候就是花哨索引
花哨索引的用法有很多
比如np.where()
还有布尔索引
'''
a = [4, 3, 5, 7, 6, 8]
indices = [0, 1, 4]
print(np.take(a, indices))
a = np.array(a)
print(a[indices])
#If indices is not one dimensional, the output also has these dimensions.
print(np.take(a, [[0, 1], [2, 3]]))

在这里插入图片描述

ndarray.put(indices, values, mode=‘raise’)

Set a.flat[n] = values[n] for all n in indices.
numpy.put(a, ind, v, mode=‘raise’)
mode{‘raise’, ‘wrap’, ‘clip’}, optional Specifies how out-of-bounds indices will behave.
‘raise’ – raise an error (default)
‘wrap’ – wrap around
‘clip’ – clip to the range
‘clip’ mode means that all indices that are too large are replaced by the index that addresses the last element along that axis. Note that this disables indexing with negative numbers. In ‘raise’ mode, if an exception occurs the target array may still be modified.
‘clip’模式意味着所有过大的索引都被沿该轴寻址最后一个元素的索引替换。 请注意,这将禁用负数索引。 在‘raise’模式下,如果发生异常,目标数组仍可能被修改。

a = np.arange(5)
print(a)
np.put(a, [0, 2], [-44, -55])
print(a)
a = np.arange(5)
print(a)
np.put(a, 22, -5, mode='clip')
print(a)
#会报错
#np.put(a, 22, -5 )

在这里插入图片描述

numpy.repeat(a, repeats, axis=None)

import numpy  as  np
print(np.repeat(3, 4))
x = np.array([[1,2],[3,4]])
print(np.repeat(x, 2))
print(np.repeat(x, 3, axis=1))
print(np.repeat(x, [1, 2], axis=0))

在这里插入图片描述

一些numpy练习题

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

龙崎流河

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值