【⼈⼯智障学习指北-002】70道NumPy⾯试题—解题出坑记基础 — Numpy ⼊门70题
题⽬来源
答案参考
⾃⼰做的答案(仅供参考+留待以后查阅)
⽬录
⼀、预储备知识点
先上⼀波在刷题过程中会遇到的知识点
#基础操作函数-从第20题左右开始⽤到
numpy.array(object, dtype=None,*, copy=True, order='K', subok=False, ndmin=0, like=None)
numpy.append(arr,values,axis)
###values must have the same dimension with the arr
#或者为a.reshape(x) x=-1时表⽰扩展为⼀维数组
#e.g. np.repeat(np.array([1,2,3]),np.array([1,2,3]))
>>> array([1,2,2,3,3,3])
>
###paras:
repeats:int or array of ints;
axis:int. The axis along which to repeat values.
By default, use the flattened input array,
and return a flat output array.
###
numpy.squeeze(a, axis=None) axis must be of length 1
np.array*3: array([1,2,3])*3-> array([3,6,9])
普通array*3:[1,2,3]*3->[1,2,3,1,2,3,1,2,3]
#axes: tuple or list of ints,元组时按照tuple顺序转职
a = np.range(16).reshape(4,4)[y0:y1,x0:x1]
#取第0维y0-y1,第1维x0-x1
a = np.range(16).reshape(4,4)[[y0,y1],[x0, x1, x3]]
#取第0维y0和y1,第1维x0, x1, x3
#求相关系数
#求差值
numpy.diff(a, n=1, axis=-1, prepend=<no value>, append=<no value>)
#求符号
numpy.sign(x,/, out=None,*, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])=<ufunc 'sign'> #⼤于0的返回1;⼩于0的返回-1;等于0的返回0
#设置数组输出形式
np.set_printoptions(precision=None, threshold=None, edgeitems=None,
linewidth=None, suppress=None, nanstr=None, infstr=None, formatter=None)
###paras:
precision 设置浮点数的精度(默认值:8)
threshold 设置显⽰的数⽬(超出部分省略号显⽰, np.nan是完全输出,默认值:1000)edgeitems 设置显⽰前⼏个,后⼏个(默认值:3)
suppress 设置是否科学记数法显⽰(默认值:False)
###
#应⽤函数
numpy.apply_along_axis(func1d, axis, arr,*args,**kwargs)
#沿着axis,对arr中每个元素应⽤函数func1d
#判断是否存在⽬标值
numpy.any(a, axis=None, out=None, keepdims=<no value>,*, where=<no value>)
#判断是否全是⽬标值
numpy.all(...)
#条件返回值:Where True, yield x, otherwise yield y.
numpy.where(condition[, x, y])
#⼀维条件下 <=>
[xv if c else yv for c, xv, yv in zip(condition, x, y)]
#去重/查单⼀值
numpy.unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None) #并按元素由⼤到⼩返回⼀个新的⽆元素重复的元组或者列表
#return_index: 返回“新”于“旧”中索引
#return_inverse: 返回“旧”于“新”中索引
#return_counts: 返回计数数量等
numpy.argwhere(a)
#返回a中⾮zero(真)的值的索引
#查最⼤值
numpy.amax(a,)#返回最⼤值
linspace numpynumpy.argmax(a, axis=None, out=None)
#返回第⼀个最⼤值的索引Index!!
#axis: 默认将array拉平;否则沿相应维度进⾏
#改变形状
numpy.ravel(a, order='C')
<=> a.ravel()
array[:,None]/ array[:,:,None]->None所在位置,数组增加⼀维
#any type -> 映射为数字类型
numpy.digitize(x, bins, right=False)#right表⽰左闭右开/左开右闭
#类型转化
numpy.pe)
numpy.asarray(a, dtype=None, order=None,*, like=None)
#将其他形式转化为array类型,e.g. lists, lists of tuples,
# tuples, tuples of tuples, tuples of lists and ndarrays
#转化为上下界内:上多上切,下多下切
numpy.clip(a, a_min, a_max, out=None,**kwargs)
#Given an interval, values outside the interval are clipped to the interval edges.
#搜索⽬标值
numpy.searchsorted(a, v, side='left', sorter=None)
#side:'left'-返回⽬标值索引(插前);'right'-返回⽬标值右值索引(插后)
#排序
numpy.sort(a, axis=-1, kind=None, order=None)#返回排序后的复制值
numpy.argsort(a, axis=-1, kind=None, order=None)
#返回排序的索引
#axis: 按照哪⼀个维度排序;None时化为⼀维数组
#kind: 排序算法 {‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’}
#产⽣随机数组
a=np.random.random((3,3))
a=np.random.randint(0,10,size=[3,3])
t3 = np.random.uniform(10,15,(3,4))# 包含最⼩值10,不包含最⼤值15
#产⽣num个均匀分布于[start, stop)内的数字
numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)
numpy.random.uniform(start=0, stop=1, num)#均匀分布
#随机选择
random.choice(a, size=None, replace=True, p=None)
#Generates a random sample from a given 1-D array
#repace:是否放回;p:每⼀个元素被选中的概率;size:输出形状
#填充
numpy.full(shape, fill_value, dtype=None, order='C',*, like=None)
#shape:int或元组;fill-value: int/array
#产⽣向量函数
class numpy.vectorize(pyfunc, otypes=None, doc=None, excluded=None, cache=False, signature=None) #连接矩阵:
np.r_=<numpy.lib.index_tricks.RClass object>纵向相加;列数相等
np.c_ / numpy.hstack(tup)横向相加;⾏数相等;#tup必须为tuple(元组)类型
#创建⼆维数组
numpy.arange([start,]stop,[step,]dtype=None,*, like=None)
print("普通⽅法")
num =[['a'for i in range(1,5)]for j in range(1,5)]
print("numpy⽅法")
num2 = np.array([np.arange(1,4),np.arange(1,4),np.arange(1,4)])
num3 = np.zeros((3,5),dtype=np.bool_)#bool8 & bool_ 默认都是false类型
#储存为txt⽂件
numpy.savetxt(fname, X, fmt='%.18e', delimiter=' ',
newline='\n', header='', footer='', comments='# ', encoding=None)
#求某⼀百分位的值
np.percentile(a, q, axis, keepdims)
###paras:
a : np数组
q :float in range of [0,100](or sequence of floats),
Percentile to compute,要计算的q分位数。
axis :那个轴上运算。
keepdims :bool是否保持维度不变。
###
np.nan——⾮空(None);np.nan==np.nan >>>False
#关于array的⼤⼩
c=[[]]
>>>len(c)
>>>1
>>>len(c[0])
>>>0
#运算:
array +/-/* array <=>按位计算(数值计算)
int(a)==int(b)->返回bool
array(a)==int(b)->为a中每个元素计算“a[i]==b”,并返回bool列表
np.dot(x, y)<=> x.dot(y)->矩阵点乘(数积)
'''
#log⽇志
l1 = [1,2,3,4]
l2 = [1,2,3,4,5]
print([x+y for x in l1 for y in l2])
>>> [2, 3, 4, 5, 6,| 3, 4, 5, 6, 7,| 4, 5, 6, 7, 8, 5, 6, 7, 8, 9]
print([[x+y for x in l1] for y in l2])
>>> [[2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8], [6, 7, 8, 9]]
'''
#关于【列表推导式】的理解
#1.遍历列表中的每⼀个元素,并进⾏相应的计算操作;返回⼀个列表
#2.简洁直观,书写便利
#3.提⾼运⾏速度
#多重循环:
[x+y for x in l1 for y in l2]从左到右<=>由外⽽内
<=>for x in l1:
for y in l2:
...
(嵌套式)
[[x+y for x in l1]for y in l2]从内⽽外<=>从内⽽外|[]改变优先级
<=>for y in l2:
for x in l1:
.
..
⼆、未理解题⽬
(1)034 如何基于两个或以上条件过滤 NumPy 数组?
难度:L3
问题:过滤 iris_2d 中满⾜ petallength(第三列)> 1.5 和 sepallength(第⼀列)< 5.0 的⾏。
# Input
url ='archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris_2d = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3])
问题详情:
#way1: ⽤ i in range(len(iris_2d)) 索引遍历的⽅法
#np.append(a, value) 发⽣未知错误
出坑⽅式:
#way2: & 按位与运算符——全真为真,并且可以计算array数据类型
url ='archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data' iris_2d = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3]) condition =(iris_2d[:,2]>1.5)&(iris_2d[:,0]<5.0)
ret = iris_2d[condition]
print(ret)
(2)054 如何使⽤ NumPy 对数组中的项进⾏排序?
难度:L2
问题:为给定的数值数组 a 创建排序。
输⼊:
np.random.seed(10)
a = np.random.randint(20, size=10)print(a)
#> [ 9 4 15 0 17 16 17 8 9 0]
期望输出:
[4260879351]
我的⽅法
#way1: 正常思路
b = np.argsort(a)
print(a[b])
#way2:
>>>>###没看懂在⼲嘛>>>###
c = a.argsort().argsort()
print(c)
(3)055 如何使⽤ NumPy 对多维数组中的项进⾏排序?
难度:L3
问题:给出⼀个数值数组 a,创建⼀个形态相同的排序数组。
输⼊:
np.random.seed(10)
a = np.random.randint(20, size=[2,5])print(a)#> [[ 9 4 15 0 17]#> [16 17 8 9 0]]期望输出:
#> [[4 2 6 0 8]
#> [7 9 3 5 1]]
#way1: 基本想法
shape = a.shape
print(shape)
a = np.shape(1,-1))
a = a.reshape(shape)
print(a)
#way2: 没看懂为何排序排两遍
>>>>###没看懂在⼲嘛>>>###
print(a.ravel().argsort().argsort().reshape(a.shape))
这道题和 #054 都是没理解他的“排序”到底是什么意思
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
python求解偏微分方程
下一篇 »
发表评论