numpy基础练习100题(01-40)
github项目地址:https://github.com/rougier/numpy-100
(1) Import the numpy package under the name np
import numpy as np
(2) Print the numpy version and the configuration
print(np.__version__)
np.show_config()
(3) Create a null vector of size 10
Z = np.zeros(10)
print(Z)
# [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
(4) How to find the memory size of any array
Z = np.zeros((10, 10))
print("%d bytes" % (Z.size * Z.itemsize))
# 800 bytes
(5) How to get the documentation of the numpy add function
np.info(np.add)
(6) Create a null vector of size 10 but the fifth value which is 1
Z = np.zeros(10)
Z[4] = 1
print(Z)
# [ 0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]
(7) Create a vector with values ranging from 10 to 49
Z = np.arange(10, 50)
print(Z)
# [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]
(8) Reverse a vector (first element becomes last)
Z = np.arange(10)
Z = Z[::-1]
print(Z)
# [9 8 7 6 5 4 3 2 1 0]
(9) Create a 3x3 matrix with values ranging from 0 to 8
Z = np.arange(9).reshape(3, 3)
print(Z)
# [[0 1 2]
# [3 4 5]
# [6 7 8]]
(10) Find indices of non-zero elements from [1,2,0,0,4,0]
nz = np.nonzero([1, 2, 0, 0, 4, 0])
print(nz)
# (array([0, 1, 4], dtype=int64),)
(11) Create a 3x3 identity matrix
Z = np.eye(3)
print(Z)
# [[ 1. 0. 0.]
# [ 0. 1. 0.]
# [ 0. 0. 1.]]
(12) Create a 3x3x3 array with random values
Z = np.random.random((3, 3, 3))
print(Z)
(13) Create a 10x10 array with random values and find the minimum and maximum values
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
Z = np.random.random(30)
m = Z.mean()
print(m)
(15) Create a 2d array with 1 on the border and 0 inside
Z = np.ones((5, 5))
Z[1:-1, 1:-1] = 0
print(Z)
# [[ 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.]]
(16) How to add a border (filled with 0’s) around an existing array?
Z = np.ones((3, 3))
Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0)
print(Z)
# [[ 0. 0. 0. 0. 0.]
# [ 0. 1. 1. 1. 0.]
# [ 0. 1. 1. 1. 0.]
# [ 0. 1. 1. 1. 0.]
# [ 0. 0. 0. 0. 0.]]
(17) What is the result of the following expression?
print(0 * np.nan)
# nan
print(np.nan == np.nan)
# False
print(np.inf > np.nan)
# False
print(np.nan - np.nan)
# nan
print(0.3 == 3 * 0.1)
# False
(18) Create a 5x5 matrix with values 1,2,3,4 just below the diagonal
Z = np.diag(1 + np.arange(4), k=-1)
print(Z)
# [[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]]
(19) Create a 8x8 matrix and fill it with a checkerboard pattern
Z = np.zeros((8, 8), dtype=int)
Z[1::2,::2] = 1
Z[::2,1::2] = 1
print(Z)
# [[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) Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element?
print(np.unravel_index(100, (6, 7, 8)))
# (1, 5, 4)
(21) Create a checkerboard 8x8 matrix using the tile function
Z = np.tile(np.array([[0, 1], [1, 0]]), (4, 4))
print(Z)
# [[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]]
(22) Normalize a 5x5 random matrix
Z = np.random.random((5, 5))
Zmax, Zmin = Z.max(), Z.min()
Z = (Z - Zmin) / (Zmax - Zmin)
print(Z)
(23) Create a custom dtype that describes a color as four unsigned bytes (RGBA)
color = np.dtype([("r", np.ubyte, 1),
("g", np.ubyte, 1),
("b", np.ubyte, 1),
("a", np.ubyte, 1)])
print(color)
# dtype([('r', 'u1'), ('g', 'u1'), ('b', 'u1'), ('a', 'u1')])
(24) Multiply a 5x3 matrix by a 3x2 matrix (real matrix product)
Z = np.dot(np.ones((5, 3)), np.ones((3, 2)))
print(Z)
# [[ 3. 3.]
# [ 3. 3.]
# [ 3. 3.]
# [ 3. 3.]
# [ 3. 3.]]
(25) Given a 1D array, negate all elements which are between 3 and 8, in place.
Z = np.arange(11)
Z[(Z >= 3) & (Z <= 8)] *= -1
print(Z)
# [ 0 1 2 -3 -4 -5 -6 -7 -8 9 10]
(26) What is the output of the following script?
print(sum(range(5), -1))
# 9
print(np.sum(range(5), -1))
# from numpy import *
# print(sum(range(5),-1))
# 10, parameter axis=-1
(27) Consider an integer vector Z, which of these expressions are legal?
Z = np.array([-1, 2, 3])
print(Z ** Z)
# [1 4 27]
print(2 << Z >> 2)
# [1 2 4]
print(Z < -Z)
# [False False False]
print(1j * Z)
# complex number
# [ 0.+1.j 0.+2.j 0.+3.j]
print(Z / 1 / 1)
# [ 1. 2. 3.]
print((Z < Z) > Z)
# array([False, False, False], dtype=bool)
(28) What are the result of the following expressions?
print(np.array(0) / np.array(0))
# python 2.7 0
# python 3.5 nan
print(np.array(0) // np.array(0))
# python 2.7 0
# python 3.5 0
print(np.array([np.nan]).astype(int).astype(float))
# python 2.7 [ -2.14748365e+09]
# python 3.5 [ -2.14748365e+09]
(29) How to round away from zero a float array?
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)?
# 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)
# False
# left part -> nan
# right part -> 1j
(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?
Z = np.arange('2016-07', '2016-08', dtype='datetime64[D]')
print(Z)
# ['2016-07-01' '2016-07-02' '2016-07-03' '2016-07-04' '2016-07-05'
# '2016-07-06' '2016-07-07' '2016-07-08' '2016-07-09' '2016-07-10'
# '2016-07-11' '2016-07-12' '2016-07-13' '2016-07-14' '2016-07-15'
# '2016-07-16' '2016-07-17' '2016-07-18' '2016-07-19' '2016-07-20'
# '2016-07-21' '2016-07-22' '2016-07-23' '2016-07-24' '2016-07-25'
# '2016-07-26' '2016-07-27' '2016-07-28' '2016-07-29' '2016-07-30'
# '2016-07-31']
(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)
# array([-1.5, -1.5, -1.5])
(36) Extract the integer part of a random array using 5 different methods
Z = np.random.uniform(0, 10, 10)
print(Z - Z % 1) # not for negative array
print(np.floor(Z)) # not for negative array
print(np.ceil(Z) - 1) # not for negative array
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)
# [[ 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.]]
(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)
# [ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
(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)