干货 | 50题带你玩转numpy

讨论 唱跳rap和web
Lv2 初级炼丹师
发布在 NumPy   1537   0
讨论 唱跳rap和web   1537   0

    这是在stackoverflow和numpy文档里汇总的numpy练习题,目的是为新老用户提供快速参考。

    1. Import the numpy package under the name np (★☆☆)

    导入numpy包,命名为np

    import numpy as np

    2. Print the numpy version and the configuration (★☆☆)

    打印numpy版本和配置

    print(np.__version__)
    np.show_config()

    3. Create a null vector of size 10 (★☆☆)

    创建一个10*10的0填充的数组

    Z = np.zeros(10)
    print(Z)

    4. How to find the memory size of any array (★☆☆)

    如何查看数组占内存大小

    Z = np.zeros((10,10))
    print("%d bytes" % (Z.size * Z.itemsize))

    5. How to get the documentation of the numpy add function from the command line? (★☆☆)

    如何在命令行下查看numpy add函数文档

    %run `python -c "import numpy; numpy.info(numpy.add)"`

    6. Create a null vector of size 10 but the fifth value which is 1 (★☆☆)

    创建一个长度为10的0数组,第5个值为1

    Z = np.zeros(10)
    Z[4] = 1
    print(Z)

    7. Create a vector with values ranging from 10 to 49 (★☆☆)

    创建一个值从10到49的数组

    Z = np.arange(10,50)
    print(Z)

    8. Reverse a vector (first element becomes last) (★☆☆)

    反转数组(第一个元素变成最后一个)

    Z = np.arange(50)
    Z = Z[::-1]
    print(Z)

    9. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆)

    创建一个从0~8的3*3矩阵

    Z = np.arange(9).reshape(3,3)
    print(Z)

    10. Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆)

    从[1,2,0,0,4,0]中找到非0元素的索引

    nz = np.nonzero([1,2,0,0,4,0])
    print(nz)

    11. Create a 3x3 identity matrix (★☆☆)

    生成一个3*3的对角矩阵

    Z = np.eye(3)
    print(Z)

    12. Create a 3x3x3 array with random values (★☆☆)

    创建一个333的随机值数组

    Z = np.random.random((3,3,3))
    print(Z)

    13. Create a 10x10 array with random values and find the minimum and maximum values (★☆☆)

    创建一个10*10的随机值数组,并找到最大最小值

    Z = np.random.random((10,10))
    Zmin, Zmax = Z.min(), Z.max()
    print(Zmin, Zmax)

    14. Create a random vector of size 30 and find the mean value (★☆☆)

    创建一个长度为30的随机值数组,并找到平均值

    Z = np.random.random(30)
    m = Z.mean()
    print(m)

    15. Create a 2d array with 1 on the border and 0 inside (★☆☆)

    创建一个四边为1,中间为0的二维数组,

    Z = np.ones((10,10))
    Z[1:-1,1:-1] = 0
    print(Z)

    16. How to add a border (filled with 0's) around an existing array? (★☆☆)

    如何给一个已经存在的数组添加边(填充0)

    Z = np.ones((5,5))
    Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0)
    print(Z)

    17. What is the result of the following expression? (★☆☆)

    看看下面表达式的结果是什么?

    print(0 * np.nan)
    print(np.nan == np.nan)
    print(np.inf > np.nan)
    print(np.nan - np.nan)
    print(np.nan in set([np.nan]))
    print(0.3 == 3 * 0.1)

    18. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆)

    创建一个5*5矩阵,对角线下方值为1,2,3,4

    Z = np.diag(1+np.arange(4),k=-1)
    print(Z)

    19. Create a 8x8 matrix and fill it with a checkerboard pattern (★☆☆)

    创建一个8*8矩阵,并用棋盘图案填充

    Z = np.zeros((8,8),dtype=int)
    Z[1::2,::2] = 1
    Z[::2,1::2] = 1
    print(Z)

    20. Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element?

    给定一个678的三维矩阵,求100个元素的索引是什么?

    print(np.unravel_index(99,(6,7,8)))

    21. Create a checkerboard 8x8 matrix using the tile function (★☆☆)

    使用tile函数创建8*8的棋盘矩阵

    Z = np.tile( np.array([[0,1],[1,0]]), (4,4))
    print(Z)

    22. Normalize a 5x5 random matrix (★☆☆)

    对一个5*5矩阵标准化处理

    Z = np.random.random((5,5))
    Z = (Z - np.mean (Z)) / (np.std (Z))
    print(Z)

    23. Create a custom dtype that describes a color as four unsigned bytes (RGBA) (★☆☆)

    新建一个dtype类型用来描述一个颜色(RGBA)

    color = np.dtype([("r", np.ubyte, 1),
                      ("g", np.ubyte, 1),
                      ("b", np.ubyte, 1),
                      ("a", np.ubyte, 1)])

    24. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) (★☆☆)

    5*3矩阵和3*2矩阵相乘

    Z = np.dot(np.ones((5,3)), np.ones((3,2)))
    print(Z)
    
    # Alternative solution, in Python 3.5 and above
    Z = np.ones((5,3)) @ np.ones((3,2))
    print(Z)

    25. Given a 1D array, negate all elements which are between 3 and 8, in place. (★☆☆)

    给定一个一维数组,将第3~8个元素取反

    # Author: Evgeni Burovski
    
    Z = np.arange(11)
    Z[(3 < Z) & (Z <= 8)] *= -1
    print(Z)

    26. What is the output of the following script? (★☆☆)

    看看下面脚本的输出是什么?

    # Author: Jake VanderPlas
    
    print(sum(range(5),-1))
    from numpy import *
    print(sum(range(5),-1))

    27. Consider an integer vector Z, which of these expressions are legal? (★☆☆)

    给定一个整数数组Z,看看下面哪个表达式是合法的?

    Z**Z
    2 << Z >> 2
    Z <- Z
    1j*Z
    Z/1/1
    Z<Z>Z

    28. What are the result of the following expressions?

    下面表达式的结果是什么?

    print(np.array(0) / np.array(0))
    print(np.array(0) // np.array(0))
    print(np.array([np.nan]).astype(int).astype(float))

    29. How to round away from zero a float array ? (★☆☆)

    如何对数组进行四舍五入操作?

    # Author: Charles R Harris
    
    Z = np.random.uniform(-10,+10,10)
    print (np.copysign(np.ceil(np.abs(Z)), Z))

    30. How to find common values between two arrays? (★☆☆)

    如何找出两个数组的共同值?

    Z1 = np.random.randint(0,10,10)
    Z2 = np.random.randint(0,10,10)
    print(np.intersect1d(Z1,Z2))

    31. How to ignore all numpy warnings (not recommended)? (★☆☆)

    如何忽略所有numpy警告?

    # Suicide mode on
    defaults = np.seterr(all="ignore")
    Z = np.ones(1) / 0
    
    # Back to sanity
    _ = np.seterr(**defaults)

    An equivalent way, with a context manager:

    with np.errstate(divide='ignore'):
        Z = np.ones(1) / 0

    32. Is the following expressions true? (★☆☆)

    下面表达式正确吗?

    np.sqrt(-1) == np.emath.sqrt(-1)

    33. How to get the dates of yesterday, today and tomorrow? (★☆☆)

    如何获得昨天、今天、明天的日期?

    yesterday = np.datetime64('today', 'D') - np.timedelta64(1, 'D')
    today     = np.datetime64('today', 'D')
    tomorrow  = np.datetime64('today', 'D') + np.timedelta64(1, 'D')

    34. How to get all the dates corresponding to the month of July 2016? (★★☆)

    如何获得2016年7月对应的所有日期?

    Z = np.arange('2016-07', '2016-08', dtype='datetime64[D]')
    print(Z)

    35. How to compute ((A+B)*(-A/2)) in place (without copy)? (★★☆)

    如何计算((A+B)*(-A/2)) ?

    A = np.ones(3)*1
    B = np.ones(3)*2
    C = np.ones(3)*3
    np.add(A,B,out=B)
    np.divide(A,2,out=A)
    np.negative(A,out=A)
    np.multiply(A,B,out=A)

    36. Extract the integer part of a random array using 5 different methods (★★☆)

    提取随机数列整数部分的五种方法

    Z = np.random.uniform(0,10,10)
    
    print (Z - Z%1)
    print (np.floor(Z))
    print (np.ceil(Z)-1)
    print (Z.astype(int))
    print (np.trunc(Z))

    37. Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆)

    创建一个5*5的矩阵,每一行值为1~4

    Z = np.zeros((5,5))
    Z += np.arange(5)
    print(Z)

    38. Consider a generator function that generates 10 integers and use it to build an array (★☆☆)

    给定一个生成器函数,可以生成10个整数,使用它来创建一个数组

    def generate():
        for x in range(10):
            yield x
    Z = np.fromiter(generate(),dtype=float,count=-1)
    print(Z)

    39. Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆)

    创建一个长度为10的数组,值为0~1之间,不包含首尾

    Z = np.linspace(0,1,11,endpoint=False)[1:]
    print(Z)

    40. Create a random vector of size 10 and sort it (★★☆)

    创建一个长度为10的数组,并做排序操作

    Z = np.random.random(10)
    Z.sort()
    print(Z)

    41. How to sum a small array faster than np.sum? (★★☆)

    如何对一个数组进行相加操作,并且速度快于np.sum

    # Author: Evgeni Burovski
    
    Z = np.arange(10)
    np.add.reduce(Z)

    42. Consider two random array A and B, check if they are equal (★★☆)

    给定两个随机数组A和B,验证它们是否相等

    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)
    print(equal)
    
    # Checking both the shape and the element values, no tolerance (values have to be exactly equal)
    equal = np.array_equal(A,B)
    print(equal)

    43. Make an array immutable (read-only) (★★☆)

    使一个数组不变(只读)

    Z = np.zeros(10)
    Z.flags.writeable = False
    Z[0] = 1

    44. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆)

    给定表示笛卡尔坐标的一个10*2的随机矩阵,将其转换为极坐标

    Z = np.random.random((10,2))
    X,Y = Z[:,0], Z[:,1]
    R = np.sqrt(X**2+Y**2)
    T = np.arctan2(Y,X)
    print(R)
    print(T)

    45. Create random vector of size 10 and replace the maximum value by 0 (★★☆)

    创建一个长度为10的随机矩阵,并将最大值替换为0

    Z = np.random.random(10)
    Z[Z.argmax()] = 0
    print(Z)

    46. Create a structured array with x and y coordinates covering the [0,1]x[0,1] area (★★☆)

    创建具有x和y坐标的结构化数组,它们覆盖[0,1] x [0,1]区域

    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))
    print(Z)

    47. Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj))

    给定两个数组X和Y,构造柯西矩阵C(Cij = 1 /(xi-yj))

    # Author: Evgeni Burovski
    
    X = np.arange(8)
    Y = X + 0.5
    C = 1.0 / np.subtract.outer(X, Y)
    print(np.linalg.det(C))

    48. Print the minimum and maximum representable value for each numpy scalar type (★★☆)

    打印每种numpy标量类型的最小和最大可表示值

    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)

    49. How to print all the values of an array? (★★☆)

    如何打印数组中所有值

    np.set_printoptions(threshold=np.nan)
    Z = np.zeros((16,16))
    print(Z)

    50. How to find the closest value (to a given scalar) in a vector? (★★☆)

    如何在数组中找到最接近给定值的值

    Z = np.arange(100)
    v = np.random.uniform(0,100)
    index = (np.abs(Z-v)).argmin()
    print(Z[index])


    本文翻译自:https://github.com/rougier/numpy-100


    版权声明:作者保留权利,不代表意本站立场。如需转载请联系本站以及作者。

    参与讨论

    回复《 干货 | 50题带你玩转numpy

    EditorJs 编辑器

    沙发,很寂寞~
    反馈
    to-top--btn