numpy100個練習解析
先放鏈接https://github.com/rougier/numpy-100/blob/master/100_Numpy_exercises.md
1. Import the numpy package under the name np
(★☆☆)
import numpy as np
可以下載Anaconda,里面帶有很多python庫。
以下默認已經引入numpy庫
2. Print the numpy version and the configuration (★☆☆)
print(np.__version__)
np.show_config()
3. Create a null vector of size 10 (★☆☆)
A=np.zeros(10)
print(A)
創建一個大小為10的零向量
4. How to find the memory size of any array (★☆☆)
A=np.zeros(10)
print(A.size * A.itemsize,"bytes")
size元素個數,itemsize每個元素的大小
5. How to get the documentation of the numpy add function from the command line? (★☆☆)
np.info(np.add)
x1 = np.arange(9.0).reshape((3, 3))
x2 = np.arange(3.0)
print(np.add(x1, x2))
'''
值得注意的是,若兩個矩陣維度不相同也可以利用add相加,結果如下所示:
[[ 0. 2. 4.]
[ 3. 5. 7.]
[ 6. 8. 10.]]
'''
6. Create a null vector of size 10 but the fifth value which is 1 (★☆☆)
A=np.zeros(10)
A[4]=1
注意第五個元素應該是A[4]
7. Create a vector with values ranging from 10 to 49 (★☆☆)
A=np.arange(10,50)
arange(start,end)表示從start到end-1
8. Reverse a vector (first element becomes last) (★☆☆)
A=np.arange(0,5)
A=A[::-1]
9. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆)
A= np.arange(9).reshape(3,3)
10. Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆)
index=np.nonzero([1,2,0,0,4,0])
print(index)
11. Create a 3x3 identity matrix (★☆☆)
A=np.eye(3)
12. Create a 3x3x3 array with random values (★☆☆)
A=np.random.random((3,3,3))
13. Create a 10x10 array with random values and find the minimum and maximum values (★☆☆)
A = np.random.random((10, 10))
B = A.max()
C = A.min()
14. Create a random vector of size 30 and find the mean value (★☆☆)
A = np.random.random(30)
print(A.mean())
15. Create a 2d array with 1 on the border and 0 inside (★☆☆)
A=np.ones((5,5))
A[1:-1,1:-1]=0
print(A)