美文网首页
numpy练习100题(26-50)

numpy练习100题(26-50)

作者: 海盗船长_coco | 来源:发表于2019-12-21 15:31 被阅读0次
  1. 下面脚本运行后的结果是什么?(提示: np.sum)
sum(range(5), -1)  # 9   #元组计算总和后再减1。1+2+3+4-1=9
np.sum(range(5), -1)  # 10 axis=-1,为负数,则从最后一个到第一个轴计数
  1. 考虑一个整数向量Z,下列表达合法的是哪个?
Z = np.arange(5)  # [0 1 2 3 4]
t1 = Z ** Z  # [  1   1   4  27 256] 0^0=1,1^1=1,2^2=4,3^3=27,4^4=256
t2 = 2 << Z >> 2  # [0 1 2 4 8]  以3为例先2<<3=16 16>>2=16/2^2=4
t3 = Z < - Z  # legal [False False False False False]
t4 = 1j * Z  # legal    [0.+0.j 0.+1.j 0.+2.j 0.+3.j 0.+4.j]    复数域
t5 = Z / 1 / 1  # legal [0. 1. 2. 3. 4.]
t6 = Z < Z > Z  # false 报错
  1. 下列表达式的结果分别是什么?
n1 = np.array(0) / np.array(0)  # 报错,n1=nan
n2 = np.array(0) // np.array(0)  # 报错,n2=0
n3 = np.array([np.nan]).astype(int).astype(float)  # [-2.14748365e+09]
  1. 如何从零位对浮点数组做舍入 ?(提示: np.uniform, np.copysign, np.ceil, np.abs)
 # 从一个均匀分布[low,high)中随机采样,注意定义域是左闭右开,即包含low,不包含high.
Z = np.random.uniform(-10, +10, 10) 
Z1 = np.copysign(np.ceil(np.abs(Z)), Z)  # 先取绝对值,再取标量的上界,最后赋予之前同样的正负号
  1. 如何找到两个数组中的共同元素?(提示: np.intersect1d)
Z1 = np.random.randint(0, 10, 10)
Z2 = np.random.randint(0, 10, 10)
result = np.intersect1d(Z1, Z2)
  1. 如何忽略所有的 numpy 警告(尽管不建议这么做)?(提示: np.seterr, np.errstate)
# defaults=np.seterr(all="ignore")
# Z=np.ones(1) /0
# _=np.seterr(**defaults)
with np.errstate(divide='ignore'):
    Z = np.ones(1) / 0
  1. 下面的表达式是正确的吗?(提示: imaginary number)
t = (np.sqrt(-1) == np.emath.sqrt(-1))  # 警告,False
  1. 如何得到昨天,今天,明天的日期?(提示: np.datetime64, np.timedelta64)
yesterday = np.datetime64('today', 'D') - np.timedelta64(1, 'D')
today = np.datetime64('today', 'D')
tomorrow = np.datetime64('today', 'D') + np.timedelta64(1, 'D')
import datetime

now = datetime.datetime.now()  #打印当前时间
now.strftime('%Y-%m-%d %H:%M:%S')
  1. 如何得到所有与2016年7月对应的日期?(提示: np.arange(dtype=datetime64['D']))
Z = np.arange('2016-07', '2016-08', dtype='datetime64[D]')
  1. 如何直接在位计算(A+B)*(-A/2)(不建立副本)?(提示: np.add(out=), np.negative(out=), np.multiply(out=), np.divide(out=))
A = np.ones(3) * 1
B = np.ones(3) * 2

np.add(A, B, out=B)
np.divide(A, 2, out=A)
np.negative(A, out=A)
np.multiply(A, B, out=A)
  1. 用五种不同的方法去提取一个随机数组的整数部分(提示: %, np.floor, np.ceil, astype, np.trunc)
Z = np.random.uniform(0, 10, 10)
Z1 = Z - Z % 1  # 浮点数减去小数部分
Z2 = np.floor(Z)  # 取其下界
Z3 = np.ceil(Z) - 1  # 取其上界减1
Z4 = Z.astype(int)  # 浮点数类型设置为整数类型
Z5 = np.trunc(Z)  # 取整使其更靠近0,-1.6->-1,1.6->1
  1. 创建一个5x5的矩阵,其中每行的数值范围从0到4(提示: np.arange)
'''
matrix=np.arange(0,5)
matrix=np.tile(matrix,(5,1))
'''
Z = np.zeros((5, 5))
Z += np.arange(5)
  1. 通过考虑一个可生成10个整数的函数,来构建一个数组(提示: np.fromiter)
'''
iterable = [i for i in range(10)]
Z = np.fromiter(iterable,float)
'''

def generate():
    for x in range(10):
        yield x  
# 关于yield关键字的解释博客https://blog.csdn.net/mieleizhi0522/article/details/82142856

Z = np.fromiter(generate(), dtype=float, count=-1)
  1. 创建一个长度为10的随机向量,其值域范围从0到1,但是不包括0和1(提示: np.linspace)
Z = np.linspace(0, 1, 11, endpoint=False)[1:]
  1. 创建一个长度为10的随机向量,并将其排序(提示: sort)
Z = np.random.random(10)
Zsort = Z.sort()

41.对于一个小数组,如何用比 np.sum更快的方式对其求和?(提示: np.add.reduce)

Z = np.arange(10)
t = np.add.reduce(Z)
  1. 对于两个随机数组A和B,检查它们是否相等(提示: np.allclose, np.array_equal)
A = np.random.randint(0, 2, 5)
B = np.random.randint(0, 2, 5)
#方法一 可以容忍一定的误差
# Assuming identical shape of the arrays and a tolerance for the comparison of values
equal = np.allclose(A, B)
# 方法2 要求每个元素严格相等
# Checking both the shape and the element values, no tolerance (values have to be exactly equal)
equal = np.array_equal(A, B)
  1. 创建一个只读数组(read-only)(提示: flags.writeable)
Z = np.zeros(10)
Z.flags.writeable = False
Z[0] = 1  # 报错 assignment destination is read-only
  1. 将笛卡尔坐标下的一个10x2的矩阵转换为极坐标形式(hint: np.sqrt, np.arctan2)
Z = np.random.random((10, 2))
X, Y = Z[:, 0], Z[:, 1]
R = np.sqrt(X ** 2 + Y ** 2)  # 半径
T = np.arctan2(Y, X)  # 弧度
angle = np.arctan2(Y, X) * 180 / np.pi  # 角度
  1. 创建一个长度为10的向量,并将向量中最大值替换为1(提示: argmax)
Z = np.random.random(10)
index = np.argmax(Z)
Z[index] = 1
  1. 创建一个结构化数组,并实现 x 和 y 坐标覆盖 [0,1]x[0,1] 区域(提示: np.meshgrid)
'''
Z = np.zeros((5, 5), [('x', float), ('y', float)])
X = np.arange(0, 0.5, 0.1)
Y = np.arange(0, 0.5, 0.1)
Z['x'], Z['y'] = np.meshgrid(X, Y)
'''
Z = np.zeros((5, 5), [('x', float), ('y', float)])
Z['x'], Z['y'] = np.meshgrid(np.linspace(0, 1, 5), np.linspace(0, 1, 5))
  1. 给定两个数组X和Y,构造Cauchy矩阵(柯西矩阵)C (Cij =1/(xi - yj))(提示: np.subtract.outer)
X = np.arange(8)
Y = X + 0.5
C = 1.0 / np.subtract.outer(X, Y)
  1. 打印每个numpy标量类型的最小值和最大值?(提示: np.iinfo, np.finfo, eps)
for dtype in [np.int8, np.int32, np.int64]:
    print(np.iinfo(dtype).min)
    print(np.iinfo(dtype).max)

for dtype in [np.float32, np.float64]:
    print(np.finfo(dtype).min)
    print(np.finfo(dtype).max)
    print(np.finfo(dtype).eps)
  1. 如何打印一个数组中的所有数值?(提示: np.set_printoptions)
np.set_printoptions(threshold=1000)
Z = np.arange(256).reshape(16, 16)
  1. 给定标量时,如何找到数组中最接近标量的值?(提示: argmin)
Z = np.random.randint(0, 50, 10)
print(Z)
scalar = 8
# 数组减去该值再取绝对值表示每个元素与标量的距离,取最小值则为最接近的值
index = np.argmin(np.abs(Z - scalar)) 
print(Z[index])

相关文章

  • numpy练习100题(26-50)

    下面脚本运行后的结果是什么?(提示: np.sum) 考虑一个整数向量Z,下列表达合法的是哪个? 下列表达式的结果...

  • numpy练习100题(76-100)

    后面的题目基本都写不出来,平时遇到的也不多,为了文章的完整性,将答案贴出。 考虑一维数组Z,构建一个二维数组, 其...

  • numpy练习100题(1-25)

    导入numpy库并简写为 np 打印numpy的版本和配置说明 创建一个长度为10的空向量 如何找到任何一个数组的...

  • numpy练习100题(51-75)

    创建一个表示位置(x,y)和颜色(r,g,b)的结构化数组(提示: dtype) 对一个表示坐标形状为(100,2...

  • 50道练习带你玩转Pandas

    受到numpy100题的启发,我们制作了pandas50题。 Pandas 是基于 NumPy 的一种数据处理工具...

  • 口算2

    口算练习2,共100题用时8分钟,对99题

  • Rust语言编程实例100题-044

    Rust语言编程实例100题-044 题目:在第41题和43题已经练习过static修饰变量的用法。今天再来练习下...

  • Rust语言编程实例100题-045

    Rust语言编程实例100题-045 题目:在第39题和42题已经练习过选择排序,插入排序,冒泡排序。今天再来练习...

  • numpy 100道通关题(二)

    34. How to get all the dates corresponding to the month o...

  • numpy 100道通关题(三)

    64. Consider a given vector, how to add 1 to each element...

网友评论

      本文标题:numpy练习100题(26-50)

      本文链接:https://www.haomeiwen.com/subject/gksgnctx.html