Numpy练习

2019-09-22 17:44:29 浏览数 (1)

开公众号啦,分享读书心得,欢迎一起交流成长。

1. Import the numpy package under the name np

代码语言:javascript复制
import numpy as np

2. Print the numpy version and the configuration

代码语言:javascript复制
print np.__version__
# np.show_config()
代码语言:javascript复制
1.10.4

3. Create a null vector of size 10

代码语言:javascript复制
E = np.empty(3) # not zero acturally
Z = np.zeros(10)
print(Z)
代码语言:javascript复制
[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]

4. How to get the documentation of the numpy add function from the command line ?

代码语言:javascript复制
!python -c"import numpy; numpy.info(numpy.add)"
代码语言:javascript复制
add(x1, x2[, out])

Add arguments element-wise.

Parameters
----------
x1, x2 : array_like
    The arrays to be added.  If ``x1.shape != x2.shape``, they must be
    broadcastable to a common shape (which may be the shape of one or
    the other).

Returns
-------
add : ndarray or scalar
    The sum of `x1` and `x2`, element-wise.  Returns a scalar if
    both  `x1` and `x2` are scalars.

Notes
-----
Equivalent to `x1`   `x2` in terms of array broadcasting.

Examples
--------
>>> np.add(1.0, 4.0)
5.0
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> np.add(x1, x2)
array([[  0.,   2.,   4.],
       [  3.,   5.,   7.],
       [  6.,   8.,  10.]])

5. Create a null vector of size 10 but the fifth value which is 1

代码语言:javascript复制
Z = np.zeros(10)
Z[4] = 1 # index just like list
print(Z)
代码语言:javascript复制
[ 0.  0.  0.  0.  1.  0.  0.  0.  0.  0.]

6. Create a vector with values ranging from 10 to 49

代码语言:javascript复制
V = np.arange(10,50) # np.arange not np.range
print(V)
代码语言:javascript复制
[10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49]

7. Reverse a vector (first element becomes last)

代码语言:javascript复制
V = np.arange(5)
V = V[::-1]
print(V)
代码语言:javascript复制
[4 3 2 1 0]

8. Create a 3x3 matrix with values ranging from 0 to 8

代码语言:javascript复制
A = np.arange(9).reshape(3,3)
print(A)
代码语言:javascript复制
[[0 1 2]
 [3 4 5]
 [6 7 8]]

9. Find indices of non-zero elements from [1,2,0,0,4,0]

代码语言:javascript复制
arr = np.array([1,2,0,0,4,0])
# list comprehension is not consise VS nonzero
nz1 = [i for i in range(len(arr)) if arr[i]==0] # a list
nz = np.nonzero(arr) # return a tuple
print nz
print nz1
代码语言:javascript复制
(array([0, 1, 4]),)
[2, 3, 5]

10. Create a 3x3 identity matrix

代码语言:javascript复制
A = np.eye(3) # for indentity matrix
B = np.identity(3) # or identity
print A
print B == A
代码语言:javascript复制
[[ 1.  0.  0.]
 [ 0.  1.  0.]
 [ 0.  0.  1.]]
[[ True  True  True]
 [ True  True  True]
 [ True  True  True]]

11. Create a 3x3x3 array with random values

代码语言:javascript复制
Z = np.random.random((3,3,3))
print Z
代码语言:javascript复制
[[[ 0.37802182  0.51185549  0.09273136]
  [ 0.35946865  0.44674969  0.76084106]
  [ 0.95776962  0.35601145  0.8915905 ]]

 [[ 0.39016786  0.63052983  0.20385571]
  [ 0.04379682  0.32062423  0.97007016]
  [ 0.4026562   0.76746884  0.84974329]]

 [[ 0.85230695  0.6368344   0.42200517]
  [ 0.98098412  0.24666028  0.86381806]
  [ 0.71310323  0.89115971  0.85823333]]]

12. Create a 10x10 array with random values and find the minimum and maximum values

代码语言:javascript复制
Z = np.random.random((10,10))
z_max, z_min = Z.max(), Z.min()
# z_max, z_min = np.max(Z), np.min(Z)
print z_max
print z_min
代码语言:javascript复制
0.996975591901
0.0148123771689

13. Create a random vector of size 30 and find the mean value

代码语言:javascript复制
Z = np.random.random(10)
m = Z.mean()
# m = np.mean(Z)
print m
代码语言:javascript复制
0.499048171998

14. Create a 2d array with 1 on the border and 0 inside

代码语言:javascript复制
Z = np.ones((5,5))
Z[1:-1, 1:-1] = 0 # indexing
print Z
代码语言:javascript复制
[[ 1.  1.  1.  1.  1.]
 [ 1.  0.  0.  0.  1.]
 [ 1.  0.  0.  0.  1.]
 [ 1.  0.  0.  0.  1.]
 [ 1.  1.  1.  1.  1.]]

15. What is the result of the following expression ?

代码语言:javascript复制
0*np.nan #nan
代码语言:javascript复制
nan
代码语言:javascript复制
np.nan == np.nan
代码语言:javascript复制
False
代码语言:javascript复制
np.inf > np.nan
代码语言:javascript复制
False
代码语言:javascript复制
np.nan - np.nan
代码语言:javascript复制
nan
代码语言:javascript复制
0.3 == 3 * 0.1
代码语言:javascript复制
False

16. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal

代码语言:javascript复制
Z = np.diag(1 np.arange(4), k=-1)
print Z
代码语言:javascript复制
[[0 0 0 0 0]
 [1 0 0 0 0]
 [0 2 0 0 0]
 [0 0 3 0 0]
 [0 0 0 4 0]]

17. Create a 8x8 matrix and fill it with a checkerboard pattern

代码语言:javascript复制
Z = np.zeros((8,8),dtype=int)
Z[1::2,0::2]=1
Z[0::2,1::2]=1
print Z
代码语言:javascript复制
[[0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]]

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

代码语言:javascript复制
print np.unravel_index(100,(6,7,8))
代码语言:javascript复制
(1, 5, 4)

19. Create a checkerboard 8x8 matrix using the tile function

代码语言:javascript复制
Z = np.tile(np.array([[0,1],[1,0]]), (4,4))
print Z
代码语言:javascript复制
[[0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]]

20. Normalize a 5x5 random matrix

代码语言:javascript复制
Z = np.random.random((5,5))
z_max, z_min = Z.max(), Z.min()
Z = (Z - z_min)/(z_max - z_min)
print Z
代码语言:javascript复制
[[ 0.35432088  0.9860153   0.73550363  0.30350038  0.10499184]
 [ 0.22329659  0.          0.54464366  0.99324627  0.98878285]
 [ 0.4801603   0.08399077  0.43971682  0.71831189  0.79786892]
 [ 1.          0.12234266  0.99166839  0.64018204  0.27405883]
 [ 0.68890375  0.26652723  0.97298099  0.94534027  0.58056662]]

21. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product)

代码语言:javascript复制
A = np.ones((5,3))
B = np.ones((3,2))
print np.dot(A,B) #or A.dot(B)
代码语言:javascript复制
[[ 3.  3.]
 [ 3.  3.]
 [ 3.  3.]
 [ 3.  3.]
 [ 3.  3.]]

22. Given a 1D array, negate all elements which are between 3 and 8, in place

代码语言:javascript复制
Z = np.arange(11)
Z[(3 < Z) & (Z <= 8)] *= -1 # boolean index
print Z
代码语言:javascript复制
[ 0  1  2  3 -4 -5 -6 -7 -8  9 10]

23. Create a 5x5 matrix with row values ranging from 0 to 4

代码语言:javascript复制
Z = np.zeros((5,5))
Z  = np.arange(5) # matrix   row
print Z
代码语言:javascript复制
[[ 0.  1.  2.  3.  4.]
 [ 0.  1.  2.  3.  4.]
 [ 0.  1.  2.  3.  4.]
 [ 0.  1.  2.  3.  4.]
 [ 0.  1.  2.  3.  4.]]

24. Consider a generator function that generates 10 integers and use it to build an array

代码语言:javascript复制
def generate():
    for x in xrange(10):
        yield x

Z = np.fromiter(generate(), dtype=float, count=-1)
print Z    
代码语言:javascript复制
[ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9.]

25. Create a vector of size 10 with values ranging from 0 to 1, both excluded

代码语言:javascript复制
Z = np.linspace(0,1,num=12,endpoint=True)[1:-1]
print Z
代码语言:javascript复制
[ 0.09090909  0.18181818  0.27272727  0.36363636  0.45454545  0.54545455
  0.63636364  0.72727273  0.81818182  0.90909091]

26. Create a random vector of size 10 and sort it

代码语言:javascript复制
Z = np.random.random(10)
Z.sort()
print Z
代码语言:javascript复制
[ 0.02092486  0.10778371  0.1580741   0.17828872  0.28058869  0.63512671
  0.70412522  0.84783555  0.93924023  0.98453489]

27. How to sum a small array faster than np.sum ?

代码语言:javascript复制
Z = np.arange(10)
%timeit np.sum(Z)
%timeit np.add.reduce(Z)
代码语言:javascript复制
The slowest run took 21.24 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 2.08 µs per loop
The slowest run took 10.39 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 1.15 µs per loop

28. Consider two random array A anb B, check if they are equal

代码语言:javascript复制
A = np.random.randint(0,2,5)
B = np.random.randint(0,2,5)
equal = np.allclose(A,B)
#Returns True if two arrays are element-wise equal within a tolerance.
print equal
代码语言:javascript复制
False

29. Make an array immutable (read-only)

代码语言:javascript复制
Z = np.zeros(10, dtype='int')
Z.flags.writeable = False
# Z[0] = 1 raise ValueError

30. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates

代码语言:javascript复制
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
代码语言:javascript复制
[ 0.97581795  0.59808053  0.4108556   0.53083869  0.27302014  0.36028763
  0.88051885  0.89321379  1.17598494  0.95036096]
[ 0.49590473  1.55488672  1.42839068  0.06888012  0.22952511  0.71644146
  0.48692754  0.42476661  0.85430172  1.30708871]

31. Create random vector of size 10 and replace the maximum value by 0

代码语言:javascript复制
Z = np.random.random(10)
Z[Z.argmax()] = 0 # Z.argmax()
print Z
代码语言:javascript复制
[ 0.79605583  0.          0.43405045  0.74944543  0.87654654  0.04885993
  0.03266925  0.09662387  0.86090177  0.48594978]

32. Create a structured array with x and y coordinates covering the [0,1]x[0,1] area

代码语言:javascript复制
Z = np.zeros((10,10), [('x',float),('y',float)])
Z['x'], Z['y'] = np.meshgrid(np.linspace(0,1,10),
                             np.linspace(0,1,10))

33. Print the minimum and maximum representable value for each numpy scalar type

代码语言:javascript复制
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)
代码语言:javascript复制
-128
127
-2147483648
2147483647
-9223372036854775808
9223372036854775807
-3.40282e 38
3.40282e 38
1.19209e-07
-1.79769313486e 308
1.79769313486e 308
2.22044604925e-16

34. How to find the closest value (to a given scalar) in an array ?

代码语言:javascript复制
Z = np.arange(100)
v = np.random.uniform(0,100)
print v
index = (np.abs(Z -v)).argmin() #argmin()
print Z[index]
代码语言:javascript复制
56.5834847025
57

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

代码语言:javascript复制
 Z = np.zeros(10, [ ('position', [ ('x', float, 1),
                                   ('y', float, 1)]),
                    ('color',    [ ('r', float, 1),
                                   ('g', float, 1),
                                   ('b', float, 1)])])
print Z
代码语言:javascript复制
[((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.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))]

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

代码语言:javascript复制
Z = np.random.random((10,2))
X,Y = np.atleast_2d(Z[:,0]), np.atleast_2d(Z[:,1])
D = np.sqrt( (X-X.T)**2   (Y-Y.T)**2)
代码语言:javascript复制
import scipy
import scipy.spatial
Z = np.random.random((10,2))
D = scipy.spatial.distance.cdist(Z,Z)
# print D

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

代码语言:javascript复制
Z = np.arange(10,dtype=np.float32)
Z = Z.astype(np.int32,copy=False) #astype
print(Z)
代码语言:javascript复制
[0 1 2 3 4 5 6 7 8 9]

38. Consider the following file,How to read it ?

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

代码语言:javascript复制
Z = np.genfromtxt('missing.dat',delimiter=",")
print Z
代码语言:javascript复制
[[  1.   2.   3.   4.   5.]
 [  6.  nan  nan   7.   8.]
 [ nan  nan   9.  10.  11.]]

39. What is the equivalent of enumerate for numpy arrays ?

代码语言:javascript复制
Z = np.arange(9).reshape(3,3)
for index,value in np.ndenumerate(Z):
    print(index,value)
代码语言:javascript复制
((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)
代码语言:javascript复制
for index in np.ndindex(Z.shape):
    print(index,Z[index])
代码语言:javascript复制
((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)

40. Generate a generic 2D Gaussian-like array

代码语言:javascript复制
X, Y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10))
D = np.sqrt(X*X Y*Y)
sigma, miu = 1.0, 0.0
G = np.exp((D-miu)**2/(2.0*sigma**2))

41. How to randomly place p elements in a 2D array ?

  • np.put
  • np.ramdom.choice
代码语言:javascript复制
n = 10
p = 3
Z = np.zeros((n,n))
index = np.random.choice(np.arange(n*n),p,replace=False)
np.put(Z,index,1)
Z
代码语言:javascript复制
array([[ 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.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  1.,  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.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])

41. How to I sort an array by the nth column ?

代码语言:javascript复制
Z = np.random.randint(0,10,(3,3))
print Z
print Z[Z[:,1].argsort()]
代码语言:javascript复制
[[8 0 9]
 [0 6 6]
 [4 4 1]]
[[8 0 9]
 [4 4 1]
 [0 6 6]]

42. Subtract the mean of each row of a matrix

代码语言:javascript复制
X = np.random.randint(4,size=(2,3))
print X
Y = X - X.mean(axis=1, keepdims=True)
print Y
代码语言:javascript复制
[[2 2 1]
 [1 1 1]]
[[ 0.33333333  0.33333333 -0.66666667]
 [ 0.          0.          0.        ]]

43. How to tell if a given 2D array has null columns ?

代码语言:javascript复制
# numpy.any(a, axis=None, out=None, keepdims=False)
# Test whether any array element along a given axis evaluates to True.
Z = np.random.randint(0,3,(3,10))
print (~Z.any(axis=0)).any()
代码语言:javascript复制
True

44. Find the nearest value from a given value in an array

代码语言:javascript复制
# numpy.ndarray.flat
# A 1-D iterator over the array.
# This is a numpy.flatiter instance, which acts similarly to, but is not a subclass of, Python’s built-in iterator object.
Z = np.random.uniform(0,1,10)
z = 0.5
m = Z.flat[np.abs(Z-z).argmin()]
print m
代码语言:javascript复制
0.494656507792

45. How to swap two rows of an array ?

代码语言:javascript复制
A = np.arange(25).reshape(5,5)
A[[0,1]] = A[[1,0]]
print A
代码语言:javascript复制
[[ 5  6  7  8  9]
 [ 0  1  2  3  4]
 [10 11 12 13 14]
 [15 16 17 18 19]
 [20 21 22 23 24]]

46. How to find the most frequent value in an array ?

代码语言:javascript复制
# np.bincount()
# Count number of occurrences of each value in array of non-negative ints.
Z = np.random.randint(0,5,10)
print Z
print np.bincount(Z)
print np.bincount(Z).argmax()
代码语言:javascript复制
[1 0 4 1 1 2 0 1 2 3]
[2 4 2 1 1]
1

47. How to get the n largest values of an array?

代码语言:javascript复制
# np.random.shuffle(x), Modify a sequence in-place
# np.argsort(x) Returns the indices that would sort an array.
# np.argpartition(x)
Z = np.arange(10)
np.random.shuffle(Z)
n = 2
print Z[np.argsort(Z)[-n:]] # slow
print Z[np.argpartition(-Z,n)[:n]] # fast
代码语言:javascript复制
[8 9]
[9 8]

0 人点赞