zoukankan      html  css  js  c++  java
  • numpy学习(五)

    练习篇(Part 5)

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

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

    运行结果:

    [((0., 0.), (0., 0., 0.)) ((0., 0.), (0., 0., 0.))
    ((0., 0.), (0., 0., 0.)) ((0., 0.), (0., 0., 0.))
    ((0., 0.), (0., 0., 0.)) ((0., 0.), (0., 0., 0.))
    ((0., 0.), (0., 0., 0.)) ((0., 0.), (0., 0., 0.))
    ((0., 0.), (0., 0., 0.)) ((0., 0.), (0., 0., 0.))]

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

    1 arr = np.random.randint(1,4,(100,2))
    2 x,y = np.atleast_2d(arr[:,0],arr[:,1])
    3 print(arr)
    4 dist = np.sqrt((x-x.T)**2+(y-y.T)**2)
    5 print(dist)

    运行结果:(太长)略

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

    1 arr = np.arange(10,dtype = np.float)
    2 arr = arr.astype(np.int32)
    3 print(arr)

    运行结果:[0 1 2 3 4 5 6 7 8 9]

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

    1,2,3,4,5
    6, , ,7,8
    , ,9,10,11

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

    运行结果:

    [[ 1 2 3 4 5]
    [ 6 -1 -1 7 8]
    [-1 -1 9 10 11]]

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

    1 arr = np.arange(9).reshape(3,3)
    2 for index, value in np.ndenumerate(arr):
    3     print(index, value)
    4 for index in np.ndindex(arr.shape):
    5     print(index, arr[index])

    运行结果:

    (0, 0) 0
    (0, 1) 1
    (0, 2) 2
    (1, 0) 3
    (1, 1) 4
    (1, 2) 5
    (2, 0) 6
    (2, 1) 7
    (2, 2) 8
    (0, 0) 0
    (0, 1) 1
    (0, 2) 2
    (1, 0) 3
    (1, 1) 4
    (1, 2) 5
    (2, 0) 6
    (2, 1) 7
    (2, 2) 8

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

    1 x,y = np.meshgrid(np.linspace(-1,1,10),np.linspace(-1,1,10))
    2 d = np.sqrt(x*x+y*y)
    3 sigma,mu = 1.0,0.0
    4 g = np.exp(-(d-mu)**2/(2.0*sigma**2))
    5 print(g)

    运行结果:(太长)略

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

    1 arr = np.zeros((10,10))
    2 np.put(arr,np.random.choice(range(10*10),3,replace=False),25)
    3 print(arr)

    运行结果:

    [[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
    [ 0. 0. 0. 0. 0. 0. 25. 0. 0. 0.]
    [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
    [ 0. 25. 0. 0. 0. 0. 0. 0. 0. 0.]
    [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
    [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
    [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
    [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
    [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
    [ 0. 25. 0. 0. 0. 0. 0. 0. 0. 0.]]

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

    1 arr = np.random.randint(1,5,(5,5))
    2 arr2 = arr - arr.mean(axis=1,keepdims=True)
    3 print(arr)
    4 print(arr2)

    运行结果:

    [[3 1 4 2 2]
    [1 1 1 4 4]
    [1 3 2 4 2]
    [4 4 1 4 3]
    [3 1 3 2 1]]
    [[ 0.6 -1.4 1.6 -0.4 -0.4]
    [-1.2 -1.2 -1.2 1.8 1.8]
    [-1.4 0.6 -0.4 1.6 -0.4]
    [ 0.8 0.8 -2.2 0.8 -0.2]
    [ 1. -1. 1. 0. -1. ]]

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

    1 arr = np.random.randint(1,10,(3,3))
    2 print(arr)
    3 arr = arr[arr[:,0].argsort()]
    4 print(arr)

    运行结果:

    [[3 6 4]
    [8 6 1]
    [9 1 9]]
    [[3 6 4]
    [8 6 1]
    [9 1 9]]

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

    1 arr = np.random.randint(0,6,(3,3))
    2 print(arr)
    3 print((~arr.any(axis=1)).any())

    运行结果:

    [[5 4 1]
    [2 4 0]
    [2 4 3]]
    False

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

    1 arr = np.random.uniform(0,1,10)
    2 print(arr)
    3 x= 0.5
    4 print(arr.flat[np.abs(arr - x).argmin()])

    运行结果:

    [0.90305224 0.48639632 0.27508478 0.54555147 0.71661301 0.21709767
    0.03780985 0.90465381 0.22589984 0.42418026]
    0.4863963171374911

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

    1 arr1 = np.arange(3).reshape(3,1)
    2 arr2 = np.arange(3).reshape(1,3)
    3 it = np.nditer([arr1,arr2,None])
    4 for x,y,z in it:
    5     z[...] = x + y
    6 print(it.operands[2])

    运行结果:

    [[0 1 2]
    [1 2 3]
    [2 3 4]]

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

     1 class NamedArray(np.ndarray):
     2     def __new__(cls, array, name="no name"):
     3         obj = np.asarray(array).view(cls)
     4         obj.name = name
     5         return obj
     6     def __array_finalize__(self,obj):
     7         if obj is None:
     8             return
     9         self.info = getattr(obj,'name','no name')
    10 
    11 arr = NamedArray(np.arange(10),"range_10")
    12 print(arr.name)

    运行结果:range_10

    64. Consider a given vector, how to add 1 to each element indexed by a second vector (be careful with repeated indices)? (★★★)

    1 arr1 = np.ones(10)
    2 arr2 = np.random.randint(1,10,20)
    3 np.add.at(arr1,arr2,1)
    4 print(arr2)
    5 print(arr1)

    运行结果:

    [5 8 2 2 5 4 4 4 7 1 3 8 5 4 9 3 7 3 1 3]
    [1. 3. 3. 5. 5. 4. 1. 3. 3. 2.]

    65. How to accumulate elements of a vector (X) to an array (F) based on an index list (I)? (★★★)

    1 arr1 = np.ones(10)
    2 arr2 = np.random.randint(1,10,10)
    3 print(arr2)
    4 print(np.bincount(arr2,arr1))

    运行结果:

    [7 4 4 2 6 9 3 1 1 7]
    [0. 2. 1. 1. 2. 0. 1. 2. 0. 1.]

  • 相关阅读:
    Rolling Hash(Rabin-Karp算法)匹配字符串
    vim下单行长文本的时候卡顿解决办法
    设置vim的默认工作路径同时与自动设当前编辑的文件所在目录为当前工作路径不冲突
    Careercup
    Careercup
    Careercup
    Careercup
    Careercup
    Careercup
    Careercup
  • 原文地址:https://www.cnblogs.com/orangecyh/p/11614312.html
Copyright © 2011-2022 走看看