美文网首页
numpy 100道通关题(二)

numpy 100道通关题(二)

作者: AlexDM | 来源:发表于2020-01-03 10:51 被阅读0次
    NumPy

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

    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 = 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 (★★☆)

    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 (★☆☆)

    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 (★★☆)

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

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

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

    41. How to sum a small array faster than 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 = 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 (★★☆)

    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 (★★☆)

    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 (★★☆)

    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))

    # 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 (★★☆)

    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])
    

    51. Create a structured array representing a position (x,y) and a color (r,g,b) (★★☆)

    Z = np.zeros(10, [ ('position', [ ('x', float, 1),
                                      ('y', float, 1)]),
                       ('color',    [ ('r', float, 1),
                                      ('g', float, 1),
                                      ('b', float, 1)])])
    print(Z)
    

    52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆)

    Z = np.random.random((10,2))
    X,Y = np.atleast_2d(Z[:,0], Z[:,1])
    D = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2)
    print(D)
    
    # Much faster with scipy
    import scipy
    # Thanks Gavin Heverly-Coulson (#issue 1)
    import scipy.spatial
    
    Z = np.random.random((10,2))
    D = scipy.spatial.distance.cdist(Z,Z)
    print(D)
    

    53. How to convert a float (32 bits) array into an integer (32 bits) in place?

    Z = np.arange(10, dtype=np.float32)
    Z = Z.astype(np.int32, copy=False)
    print(Z)
    

    54. How to read the following file? (★★☆)

    from io import StringIO
    
    # Fake file
    s = StringIO("""1, 2, 3, 4, 5\n
                    6,  ,  , 7, 8\n
                     ,  , 9,10,11\n""")
    Z = np.genfromtxt(s, delimiter=",", dtype=np.int)
    print(Z)
    

    55. What is the equivalent of enumerate for numpy arrays? (★★☆)

    Z = np.arange(9).reshape(3,3)
    for index, value in np.ndenumerate(Z):
        print(index, value)
    for index in np.ndindex(Z.shape):
        print(index, Z[index])
    

    56. Generate a generic 2D Gaussian-like array (★★☆)

    X, Y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10))
    D = np.sqrt(X*X+Y*Y)
    sigma, mu = 1.0, 0.0
    G = np.exp(-( (D-mu)**2 / ( 2.0 * sigma**2 ) ) )
    print(G)
    

    57. How to randomly place p elements in a 2D array? (★★☆)

    # Author: Divakar
    
    n = 10
    p = 3
    Z = np.zeros((n,n))
    np.put(Z, np.random.choice(range(n*n), p, replace=False),1)
    print(Z)
    

    58. Subtract the mean of each row of a matrix (★★☆)

    # Author: Warren Weckesser
    
    X = np.random.rand(5, 10)
    
    # Recent versions of numpy
    Y = X - X.mean(axis=1, keepdims=True)
    
    # Older versions of numpy
    Y = X - X.mean(axis=1).reshape(-1, 1)
    
    print(Y)
    

    59. How to I sort an array by the nth column? (★★☆)

    # Author: Steve Tjoa
    
    Z = np.random.randint(0,10,(3,3))
    print(Z)
    print(Z[Z[:,1].argsort()])
    

    60. How to tell if a given 2D array has null columns? (★★☆)

    # Author: Warren Weckesser
    
    Z = np.random.randint(0,3,(3,10))
    print((~Z.any(axis=0)).any())
    

    61. Find the nearest value from a given value in an array (★★☆)

    Z = np.random.uniform(0,1,10)
    z = 0.5
    m = Z.flat[np.abs(Z - z).argmin()]
    print(m)
    

    62. Considering two arrays with shape (1,3) and (3,1), how to compute their sum using an iterator? (★★☆)

    A = np.arange(3).reshape(3,1)
    B = np.arange(3).reshape(1,3)
    it = np.nditer([A,B,None])
    for x,y,z in it: z[...] = x + y
    print(it.operands[2])
    

    63. Create an array class that has a name attribute (★★☆)

    class NamedArray(np.ndarray):
        def __new__(cls, array, name="no name"):
            obj = np.asarray(array).view(cls)
            obj.name = name
            return obj
        def __array_finalize__(self, obj):
            if obj is None: return
            self.info = getattr(obj, 'name', "no name")
    
    Z = NamedArray(np.arange(10), "range_10")
    print (Z.name)
    

    https://github.com/rougier/numpy-100

    相关文章

      网友评论

          本文标题:numpy 100道通关题(二)

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