大體上介紹一下這個包。
1.簡介
NumPy 是一個 Python 包。 它代表 “Numeric Python”。 它是一個由多維數組對象和用於處理數組的例程集合組成的庫。
2.安裝
python官方版本,可以通過pip或者源碼安裝
推薦使用anaconda,這是發行版的python,內含了numpy等重要第三方庫。
anaconda安裝使用見https://blog.csdn.net/zhouchen1998/article/details/81382006
3.創建ndarray對象
這是這個模塊最核心的對象,表示一個n維數組,它是相同類型的數據集合。
numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0
其中,
object 任何暴露數組接口方法的對象都會返回一個數組或任何(嵌套)序列。
dtype 數組的所需數據類型,可選。
copy 可選,默認爲true,對象是否被複制。
order C(按行)、F(按列)或A(任意,默認)。
subok 默認情況下,返回的數組被強制爲基類數組。 如果爲true,則返回子類。
ndimin 指定返回數組的最小維數。
import numpy as np
# 一維
a = np.array([1, 2, 3])
print(a)
# n維
b = np.array([[1, 2, 3], [4, 5, 6]])
print(b)
# 帶數據類型設置
c = np.array([1, 2, 3], dtype=complex)
print(c)
# 帶最小維度設置
d = np.array([[1, 2, 3], [4, 5, 6]], ndmin=3)
print(d)
4.dtype的使用
首先,numpy提供了比python更加豐富的標量數據類型。
numpy.dtype(object, align, copy)
其中,
Object:被轉換爲數據類型的對象。
Align:如果爲true,則向字段添加間隔,使其類似 C 的結構體。
Copy: 生成dtype對象的新副本,如果爲flase,結果是內建數據類型對象的引用。
import numpy as np
# 內置轉換
dt1 = np.dtype(np.int32)
print(dt1)
# 簡略寫法
dt2 = np.dtype('i4')
print(dt2)
# 結構化數據
dt3 = np.dtype([('year', np.int16)])
print(dt3)
a = np.array([(1998, ), (2000, ), (2012, )], dtype=dt3)
print(a)
# 結構化數據的字段訪問
print(a['year'])
# 完整的結構示例,類似C語言結構體
date = np.dtype([('year', np.int32), ('month', np.int8), ('day', np.int8)])
b = np.array([(1998, 5, 26), (2000, 5, 26), (2014, 5, 26)])
print(b)
5.ndarray屬性
shape:包含數組維度的元組
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a)
print(a.shape)
# a.shape = (3, 2)
# print(a)
# 等價於下面
c = a.reshape(3, 2)
print(c)
ndim: 維度數
a = np.arange(24)
print(a.ndim)
b = a.reshape(2, 4, 3)
print(b.ndim)
itemsize:每個元素佔字節數
flags:數組的幾個狀態
6.特殊數組的創建
numpy.empty(shape, dtype = float, order = 'C') 沒有初值但是分配空間的數組
numpy.zeros(shape, dtype = float, order = 'C') 初值全爲0的數組
numpy.ones(shape, dtype = None, order = 'C') 初值全爲1的數組
其中,
shape是形狀,如(2,2)表示二行二列
dtype表示數據類型
order表示組織風格
其餘數值類型數組如arange不細說
import numpy as np
a = np.empty((2, 2), dtype=np.int8, order='C')
print(a)
b = np.zeros((2, 2), dtype=np.int8, order='C')
print(b)
c = np.ones((2, 2), dtype=np.int8, order='C')
print(c)
7.從python內置數據類型轉換爲numpy的數組
asarray
numpy.asarray(a, dtype = None, order = None)
其中,
a 任意形式的輸入參數,比如列表、列表的元組、元組、元組的元組、元組的列表
dtype,order 不再說明
import numpy as np
# 列表
x = [1, 2, 3]
a = np.asarray(x)
print(a)
# 元組
a = np.asarray(x)
print(a)
# 元組列表
x = [(1, 2, 3), (4, 5)]
a = np.asarray(x)
print(a)
frombuffer
numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0)
其中,
buffer 任何暴露緩衝區接口的對象
dtype 同上
count 需要讀取的數據數量,默認爲-1,讀取所有數據
offset 需要讀取的起始位置,默認爲0
fromiter
numpy.fromiter(iterable, dtype, count = -1)
其中,
iterable 任何可迭代對象
dtype 返回數組的數據類型
count 需要讀取的數據數量,默認爲-1,讀取所有數據