numpy 學習筆記
阿新 • • 發佈:2018-05-26
int 內存 col scipy lis python eve clas 行數
numpy 學習筆記
導入 numpy 包
import numpy as np
聲明 ndarray 的幾種方法
方法一,從list中創建
l = [[1,2,3], [4,5,6], [7,8,9]]
matrix = np.array(l)
print(matrix)
[[1 2 3]
[4 5 6]
[7 8 9]]
方法二,指定維度,不賦值
matrix = np.ndarray(shape=(3,4))
print(matrix)
[[9.66308774e-312 2.47032823e-322 0.00000000e+000 0.00000000e+000] [1.89146896e-307 2.42336543e-057 5.88854416e-091 9.41706373e-047] [5.44949034e-067 1.46609735e-075 3.99910963e+252 3.43567991e+179]]
由上述的輸出可見,矩陣內部的值未初始化,其實這都是原來對應內存地址中的數值
方法三,指定維度,初始化成全零的矩陣
matrix = np.zeros(shape=[3,4])
print(matrix)
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
方法四,使用默認參數(arange),生成從0至arange的一組數據
matrix = np.arange(12).reshape(3,4)
print(matrix)
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
數值計算
操作全部元素
print(matrix)
print("after times 10 on every elements:" )
print(matrix * 10)
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
after times 10 on every elements:
[[ 0 10 20 30]
[ 40 50 60 70]
[ 80 90 100 110]]
print(matrix)
print("after plus 10 on every elements:")
print(matrix + 10)
[[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] after plus 10 on every elements: [[10 11 12 13] [14 15 16 17] [18 19 20 21]]
操作部分元素
print(matrix)
print("after times 10 on every elements:")
print(matrix[1] * 10)
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
after times 10 on every elements:
[40 50 60 70]
索引部分元素
取一行數據
print(matrix)
print("a line of a matrix:")
print(matrix[1])
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
a line of a matrix:
[4 5 6 7]
取一列數據
以行的形式返回,得到一個行向量
print(matrix)
print("a column of a matrix:")
print(matrix[:,1])
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
a column of a matrix:
[1 5 9]
以列的形式返回,得到一個列向量
print(matrix)
print("a column of a matrix:")
print(matrix[:,1:2])
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
a column of a matrix:
[[1]
[5]
[9]]
參考資料
《利用python進行數據分析》. https://book.douban.com/subject/25779298/
Numpy. Quickstart tutorial. https://docs.scipy.org/doc/numpy/user/quickstart.html
numpy 學習筆記