numpy函數(shù)指南:一覽numpy庫中常用的函數(shù)及其功能,需要具體代碼示例
引言:
NumPy是Python中一個用于科學(xué)計算的核心庫,提供了大量高效的數(shù)組操作函數(shù)和工具。在數(shù)據(jù)處理、數(shù)值計算和機器學(xué)習(xí)等領(lǐng)域都得到了廣泛應(yīng)用。本文將介紹一些常用的NumPy函數(shù),以及它們的具體功能和用法,并提供相應(yīng)的代碼示例。
一、創(chuàng)建數(shù)組的函數(shù)
- numpy.array()
numpy.array()函數(shù)用于創(chuàng)建一個數(shù)組。可以接收一個列表、元組、數(shù)字或其他數(shù)組,創(chuàng)建一個指定形狀和數(shù)據(jù)類型的數(shù)組。
代碼示例:
import numpy as np
創(chuàng)建一個1維數(shù)組
a = np.array([1, 2, 3])
print(a) # 輸出:[1 2 3]
創(chuàng)建一個2維數(shù)組
b = np.array([[1, 2, 3], [4, 5, 6]])
print(b)
”’
輸出:
[[1 2 3]
[4 5 6]]
”’
- numpy.zeros()
numpy.zeros()函數(shù)用于創(chuàng)建一個指定大小的數(shù)組,并將數(shù)組元素初始化為0。
代碼示例:
import numpy as np
創(chuàng)建一個3×3的全0數(shù)組
a = np.zeros((3, 3))
print(a)
”’
輸出:
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
”’
- numpy.ones()
numpy.ones()函數(shù)用于創(chuàng)建一個指定大小的數(shù)組,并將數(shù)組元素初始化為1。
代碼示例:
import numpy as np
創(chuàng)建一個2×2的全1數(shù)組
a = np.ones((2, 2))
print(a)
”’
輸出:
[[1. 1.]
[1. 1.]]
”’
二、數(shù)組操作的函數(shù)
- numpy.shape()
numpy.shape()函數(shù)用于獲取數(shù)組的形狀。
代碼示例:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.shape) # 輸出:(2, 3)
- numpy.reshape()
numpy.reshape()函數(shù)用于改變數(shù)組的形狀。
代碼示例:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
res = arr.reshape((2, 3))
print(res)
”’
輸出:
[[1 2 3]
[4 5 6]]
”’
- numpy.concatenate()
numpy.concatenate()函數(shù)用于將兩個或多個數(shù)組沿指定軸連接在一起。
代碼示例:
import numpy as np
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6]])
res = np.concatenate((a, b), axis=0)
print(res)
”’
輸出:
[[1 2]
[3 4]
[5 6]]
”’
三、數(shù)學(xué)運算的函數(shù)
- numpy.add()
numpy.add()函數(shù)用于對兩個數(shù)組進行逐元素的加法運算。
代碼示例:
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
res = np.add(a, b)
print(res) # 輸出:[5 7 9]
- numpy.subtract()
numpy.subtract()函數(shù)用于對兩個數(shù)組進行逐元素的減法運算。
代碼示例:
import numpy as np
a = np.array([4, 5, 6])
b = np.array([1, 2, 3])
res = np.subtract(a, b)
print(res) # 輸出:[3 3 3]
- numpy.dot()
numpy.dot()函數(shù)用于計算兩個數(shù)組的點積。
代碼示例:
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
res = np.dot(a, b)
print(res) # 輸出:32
結(jié)論:
本文介紹了一些常用的NumPy函數(shù)及其功能和用法,并提供了相應(yīng)的代碼示例。通過使用這些函數(shù),我們可以方便地創(chuàng)建數(shù)組、進行數(shù)組操作和進行數(shù)學(xué)運算。NumPy在科學(xué)計算中發(fā)揮了重要的作用,希望本文能對讀者對NumPy的學(xué)習(xí)和使用有所幫助。
參考資料:
1.《NumPy官方文檔》,https://numpy.org/doc/
2.《Python科學(xué)計算庫NumPy的使用》,https://www.runoob.com/numpy/numpy-tutorial.html






