numpy中級學習

"""
numpy下的常見方法:
    all,any,argmax, argmin,argpartition,argsort,choose, clip,
    compress,copy,cumprod, cumsum,diagonal,imag,max, mean,min,
    nonzero,partition, prod,ptp,put,ravel,real, repeat,reshape,
    round, searchsorted,sort,squeeze,std, sum,swapaxes,take,trace,
    transpose,var。

ndarray屬性:
    ndarray.flags有關陣列的內存佈局的信息。
    ndarray.shape數組維度的元組。
    ndarray.strides在遍歷數組時在每個維度上步進的字節元組。
    ndarray.ndim數組維數。
    ndarray.data指向數組數據開頭的Python緩衝區對象。
    ndarray.size數組中元素的數量。
    ndarray.itemsize一個數組元素的長度(以字節爲單位)。
    ndarray.nbytes數組元素消耗的總字節數。
    ndarray.base如果內存來自其他對象,則爲基礎對象。
    ndarray.dtype數組元素的數據類型。
    ndarray.T轉置數組。
    ndarray.real數組的實部。
    ndarray.imag數組的虛部。
    ndarray.flat數組上的一維迭代器。
    ndarray.ctypes一個用於簡化數組與ctypes模塊的交互的對象。
    
ndarray轉換:
    ndarray.item(*args)將數組的元素複製到標準Python標量並返回。
    ndarray.tolist()將數組作爲a.ndimPython標量的-levels深度嵌套列表返回。
    ndarray.itemset(*args)將標量插入數組中(如果可能,將標量強制轉換爲數組的dtype)
    ndarray.tobytes([order])在數組中構造包含原始數據字節的Python字節。
    ndarray.tofile(fid[, sep, format])將數組以文本或二進制形式寫入文件(默認)。
    ndarray.dumps()以字符串形式返回數組的泡菜。
    ndarray.astype(dtype[, order, casting, …])數組的副本,強制轉換爲指定的類型。
    ndarray.byteswap([inplace])交換數組元素的字節
    ndarray.copy([order])返回數組的副本。
    ndarray.view([dtype, type])具有相同數據的數組的新視圖。
    ndarray.getfield(dtype[, offset])以給定類型返回給定數組的字段。
    ndarray.fill(value)用標量值填充數組。
    
    
ndarray形狀操作:
    ndarray.reshape(shape[, order])返回一個數組,其中包含具有相同形狀的相同數據。
    ndarray.resize(new_shape[, refcheck])就地更改數組的形狀和大小。
    ndarray.transpose(*axes)就地更改數組的形狀和大小。
    ndarray.swapaxes(axis1, axis2)返回軸1和軸2互換的數組視圖。
    ndarray.flatten([order])返回摺疊成一維的數組副本。
    ndarray.ravel([order])返回一個展平的數組。
    ndarray.squeeze([axis])從形狀除去單維輸入一個。

ndarray選擇和操作:
  ndarray.take(indices, axis=None, out=None, mode='raise')返回來自的元素構成的數組一個在給定的索引。

ndarray方法:
    ndarray.max([axis, out, keepdims, initial, …])沿給定軸返回最大值。
    ndarray.argmax([axis, out])沿給定軸返回最大值的索引。
    ndarray.min([axis, out, keepdims, initial, …])沿給定軸返回最小值。
    ndarray.argmin([axis, out])返回最小值的索引沿給定軸線一個。
    ndarray.ptp([axis, out, keepdims])沿給定軸的峯到峯(最大值-最小值)值。
    ndarray.clip([min, max, out])返回值限制爲的數組。[min, max]
    ndarray.conj()將所有元素複數共軛
    ndarray.round([decimals, out])返回一個與舍入到小數的給定數目的每個元素。
    ndarray.trace([offset, axis1, axis2, dtype, out])返回數組對角線的和。
    ndarray.sum([axis, dtype, out, keepdims, …])返回給定軸上數組元素的總和。
    ndarray.cumsum([axis, dtype, out])返回沿給定軸的元素的累加和。
    ndarray.mean([axis, dtype, out, keepdims])返回沿給定軸的數組元素的平均值。
    ndarray.var([axis, dtype, out, ddof, keepdims])返回沿給定軸的數組元素的方差。
    ndarray.std([axis, dtype, out, ddof, keepdims])返回沿給定軸的數組元素的標準偏差。
    ndarray.prod([axis, dtype, out, keepdims, …])返回給定軸上數組元素的乘積
    ndarray.cumprod([axis, dtype, out])返回沿給定軸的元素的累積積。
    ndarray.all([axis, out, keepdims])如果所有元素的評估結果爲True,則返回True。
    ndarray.any([axis, out, keepdims])如果任何元素,則返回true 一個評估爲True。
"""
<class 'numpy.ndarray'>
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

(2, 3)
(12, 4)
2
<memory at 0x00000188A8DCAE48>
6
4
24
int32
<numpy.core._internal._ctypes object at 0x00000188A9E152C8>
[[1 4]
 [2 5]
 [3 6]]
[[1 2 3]
 [4 5 6]]
[[0 0 0]
 [0 0 0]]
# ndarray屬性:
import numpy as np
x=np.array([[1,2,3],[4,5,6]],np.int32)

# print(type(x))#顯示對象類型
# # <class 'numpy.ndarray'>:就有一下屬性

print(x)
'''
[[1 2 3]
 [4 5 6]]
'''

print(x.flags)#有關陣列的內存佈局的信息
'''
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

'''
print(x.shape)#數組維度的元組【對象形狀】
'''
(2, 3)
'''
print(x.strides)#在遍歷數組時在每個維度上步進的字節元組
'''
(12, 4)
'''
print(x.ndim)#數組維數
'''
2
'''
print(x.data)#指向數組數據開頭的Python緩衝區對象
'''
<memory at 0x0000025B7C2A9C88>
'''
print(x.size)#數組中元素的數量
'''
6
'''
print(x.itemsize)#一個數組元素的長度(以字節爲單位)
'''
4
'''
print(x.nbytes)#數組元素消耗的總字節數
'''
24
'''
print(x.dtype)#數組元素的數據類型
'''
int32
'''
print(x.ctypes)#一個用於簡化數組與ctypes模塊的交互的對象
'''
<numpy.core._internal._ctypes object at 0x0000025B7D2BDF88>
'''
print(x.T)#轉置數組
'''
[[1 4]
 [2 5]
 [3 6]]
'''
print(x.real)#數組的實部
'''
[[1 2 3]
 [4 5 6]]
'''
print(x.imag)#數組的虛部
'''
[[0 0 0]
 [0 0 0]]
'''
# ndarray轉換:
import numpy as np
x=np.array([[1,2,3],[4,5,6]],np.int32)

print(x.item(1))#第一行第二列數據
'''
2
'''
print(x.item((1,2)))#第二行第三列數據
'''
6
'''
print(x.tolist())#把ndarray類型轉換爲list
print(type(x.tolist()))
'''
[[1, 2, 3], [4, 5, 6]]
<class 'list'>
'''
x.itemset(5,9)#類似展平後替換數據
print(x)#顯示結果
'''
[[1 2 3]
 [4 5 9]]
'''
print(x.tobytes())#轉換爲字節
'''
b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00'
'''
x.tofile("x.bin")##類似展平後保存文件
tmp=np.fromfile("x.bin",dtype=np.int32)#讀取文件
print(tmp)#顯示結果
'''
[1 2 3 4 5 6]
'''
tmp=x.astype(np.int64)#強制轉換爲指定的類型
print(tmp.dtype)#顯示結果
'''
int64
'''
tmp=x.copy()#數組的副本【numpy的深拷貝】
print(tmp)#顯示結果
tmp[0]=99
print(tmp)
print(x)#原始數據不變
'''
[[1 2 3]
 [4 5 6]]
[[99 99 99]
 [ 4  5  6]]
[[1 2 3]
 [4 5 6]]
'''
tmp=x.view()#具有相同數據的數組的新視圖【numpy的淺拷貝】
print(tmp)#顯示結果
tmp[0]=99
print(tmp)
print(x)#原始數據也隨着改變
'''
[[1 2 3]
 [4 5 6]]
[[99 99 99]
 [ 4  5  6]]
[[99 99 99]
 [ 4  5  6]]
'''
map(hex,x)#以十六進制表示內存中的數據
print(x)#對原始數據不影響
print(x.byteswap(True))#查看x存儲在內存的數據
'''
[[1 2 3]
 [4 5 6]]
[[ 16777216  33554432  50331648]
 [ 67108864  83886080 100663296]]
'''
print(x)
x.fill(0)#填充0,就是把全部數據換成0
print(x)#顯示結果
'''
[[1 2 3]
 [4 5 6]]
[[0 0 0]
 [0 0 0]]
'''
import pickle
tmp=x.dumps()#轉換類型
# print(tmp)#一大推的bytes類型數據
print(type(x))#<class 'numpy.ndarray'>
print(type(tmp))#<class 'bytes'>
print(pickle.loads(tmp))#加載並顯示數據
'''
<class 'numpy.ndarray'>
<class 'bytes'>
[[1 2 3]
 [4 5 6]]
'''


x2 = np.diag([1.+1.j]*2)#輸出矩陣的對角線元素
x2[1, 1] = 2 + 4.j
print(x2)#顯示結果
print(type(x2))
print(x2.dtype)#複數類型
print(x2[0,0].itemsize)##一個數組元素的長度(以字節爲單位)
print(x2.getfield(np.float64))#offset默認爲0
print(x2.getfield(np.float64,offset=8))#獲取複數前面的數字
'''
[[1.+1.j 0.+0.j]
 [0.+0.j 2.+4.j]]
<class 'numpy.ndarray'>
complex128
16
[[1. 0.]
 [0. 2.]]
[[1. 0.]
 [0. 4.]]
'''
print()
# ndarray形狀操作:
# a=np.arange(12).reshape((3,4))
# print(a)#顯示結果
# print(np.reshape(a, (4, 3)))#橫着獲取數據
# print(np.reshape(a, (4, 3), order='F'))#斜向下獲取
'''
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]
[[ 0  5 10]
 [ 4  9  3]
 [ 8  2  7]
 [ 1  6 11]]
'''
# a=np.arange(12).reshape((3,4))
# print(a)
# a.resize(2,6)#在本身上進行操作
# print(a)
'''
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
[[ 0  1  2  3  4  5]
 [ 6  7  8  9 10 11]]
'''

# a=np.arange(12).reshape((3,4))
# print(a.transpose((1,0)))#把列轉換爲行
# b=np.arange(16).reshape((2,2,4))
# print(b.transpose(1,2,0))#兩對三位數組的轉換並重組
# print(b.swapaxes(2,1))#自己三維數組的轉換並重組
'''
[[ 0  4  8]
 [ 1  5  9]
 [ 2  6 10]
 [ 3  7 11]]
[[[ 0  8]
  [ 1  9]
  [ 2 10]
  [ 3 11]]

 [[ 4 12]
  [ 5 13]
  [ 6 14]
  [ 7 15]]]
[[[ 0  4]
  [ 1  5]
  [ 2  6]
  [ 3  7]]

 [[ 8 12]
  [ 9 13]
  [10 14]
  [11 15]]]
'''
# a=np.arange(12).reshape((3,4))
# b=np.arange(16).reshape((2,2,4))
# print(a.flatten())#展平數組【類似numpy的copy】
# print(b.flatten())#展平數組
# print(a.ravel())#展平數組【類似numpy的view】
# print(b.ravel())#展平數組
# c=np.arange(3).reshape(3,1)
# print(a.squeeze())#展平數組【只能對維數爲1的維度降維】
# print(b.squeeze())#展平數組【只能對維數爲1的維度降維】
# print(c.squeeze())#可以展平
'''
[ 0  1  2  3  4  5  6  7  8  9 10 11]
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15]
[ 0  1  2  3  4  5  6  7  8  9 10 11]
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15]
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
[[[ 0  1  2  3]
  [ 4  5  6  7]]

 [[ 8  9 10 11]
  [12 13 14 15]]]
[0 1 2]
'''
print()
# ndarray選擇和操作:
# numpy.take(a, indices, axis=None, out=None, mode='raise')沿軸從數組中獲取元素。
# numpy.put(a, ind, v, mode='raise')用給定值替換數組的指定元素。
# numpy.repeat(a, repeats, axis=None)重複數組的元素。
# numpy.choose(a, choices, out=None, mode='raise')從索引數組和一組數組中構造一個數組以供選擇。
# numpy.sort(a, axis=-1, kind=None, order=None)返回數組的排序副本。
# numpy.argsort(a, axis=-1, kind=None, order=None)返回將對數組進行排序的索引。
# numpy.searchsorted(a, v, side='left', sorter=None)查找應在其中插入元素以保持順序的索引。
# numpy.nonzero(a)返回非零元素的索引。
# numpy.compress(condition, a, axis=None, out=None)沿給定軸返回數組的選定切片。
# numpy.diagonal(a, offset=0, axis1=0, axis2=1)返回指定的對角線


a = np.arange(1,6)#原始數據
indices = [0, 1, 4]#要獲取的下標列表
print(np.take(a, indices))#根據下標取值,返回一維數組
print(a[indices])#同上
indices=[[0, 1], [3, 4]]
print(np.take(a, indices))#根據下標取值,返回二維數組
'''
[1 2 5]
[1 2 5]
[[1 2]
 [4 5]]
'''
a = np.arange(5)
np.put(a, [0, 2], [-44, -55])
print(a)
b = np.arange(5)
np.put(b, 22, -5, mode='clip')#clip:修剪(下標超出就放在最後一位)
print(b)
'''
[1 2 5]
[1 2 5]
[[1 2]
 [4 5]]
[-44   1 -55   3   4]
[ 0  1  2  3 -5]
'''
print(np.repeat(3, 4))#創建一維數組,3重複4次
x = np.array([[1,2],[3,4]])
print(np.repeat(x, 2))#展平數據後,再重複每個數值2次
print(np.repeat(x, 3, axis=1))#不展平數據,二維數據的每一行數值重複3次
print(np.repeat(x, [1, 2], axis=0))#不展平數據,二維數組的除了第一行每一行重複2次
'''
[3 3 3 3]
[1 1 2 2 3 3 4 4]
[[1 1 1 2 2 2]
 [3 3 3 4 4 4]]
[[1 2]
 [3 4]
 [3 4]]
'''
choices = [[0, 1, 2, 3], [10, 11, 12, 13],[20, 21, 22, 23], [30, 31, 32, 33]]
choices=np.array(choices)
print(choices)
print(np.choose([2, 3, 1, 0], choices))#獲取第一列第三行數值,第二列第四行數值....
print(np.choose([2, 4, 1, 0], choices, mode='clip'))#clip:修剪(下標超出就放在最後一位)
'''
[[ 0  1  2  3]
 [10 11 12 13]
 [20 21 22 23]
 [30 31 32 33]]
[20 31 12  3]
[20 31 12  3]
'''
a = np.array([[1,4],[3,1]])
print(np.sort(a, axis=None))#類似展平再排序
print(np.sort(a, axis=0))#按列排序
print(np.sort(a, axis=1))#按行排序
'''
[1 1 3 4]
[[1 1]
 [3 4]]
[[1 4]
 [1 3]]
'''
x = np.array([3, 1, 2])
print(np.argsort(x))#返回數值排序大小的下標
x = np.array([[0, 3], [1, 2]])
print(np.argsort(x, axis=0))#返回數值排序大小的下標【按列排序】
print(np.argsort(x, axis=1))#返回數值排序大小的下標【按行排序】
'''
[1 2 0]
[[0 1]
 [1 0]]
[[0 1]
 [0 1]]
'''
print(np.searchsorted([1,2,3,4,5], 3))#插入並查詢下標,默認插入到左邊
print(np.searchsorted([1,2,3,4,5], 3, side='right'))#插入到右邊,並返回下標
print(np.searchsorted([1,2,3,4,5], [-10, 10, 2, 3]))#不是同時插入
'''
2
3
[0 5 1 2]
'''
x = np.array([[3, 0, 0], [0, 4, 0], [5, 6, 0]])
tmp=np.nonzero(x)#返回非零元素的索引。
print(tmp[0])#二維數組的行
print(tmp[1])#二維數組的列
print(np.transpose(np.nonzero(x)))#顯示更清楚的下標
print(x[np.nonzero(x)])#獲取非零元素的值
'''
[0 1 2 2]
[0 1 0 1]
[[0 0]
 [1 1]
 [2 0]
 [2 1]]
[3 4 5 6]
'''
a = np.array([[1, 2], [3, 4], [5, 6]])
print(np.compress([0, 1], a, axis=0))#除了0是False,其他的都是True
print(np.compress([False, True], a, axis=0))#同上【讀取第二行】
print(np.compress([0, 1], a, axis=1))#除了0是False,其他的都是True
print(np.compress([False, True], a, axis=1))#同上【讀取第二列】
print(np.compress([0, 1, 1], a, axis=0))#除了0是False,其他的都是True
print(np.compress([False, True, True], a, axis=0))#同上【讀取第二,第三行】
# print(np.compress([False, True, True], a, axis=1))#【出錯:沒有第三列】
'''
[[3 4]]
[[3 4]]
[[2]
 [4]
 [6]]
[[2]
 [4]
 [6]]
[[3 4]
 [5 6]]
[[3 4]
 [5 6]]
'''
a = np.arange(9).reshape(3,3)
print(a)
print(a.diagonal())#斜向下的對角線
print(a.diagonal(1))
print(a.diagonal(2))
'''
[[0 1 2]
 [3 4 5]
 [6 7 8]]
[0 4 8]
[1 5]
[2]
'''
a = np.arange(27).reshape(3,3,3)
print(a)
print(a.diagonal(0))#三維數組的第一個的對角線
print(a.diagonal(1))#三維數組的前第兩個第二行
print(a.diagonal(2))#三維數組的第一個第三行
'''
[[[ 0  1  2]
  [ 3  4  5]
  [ 6  7  8]]

 [[ 9 10 11]
  [12 13 14]
  [15 16 17]]

 [[18 19 20]
  [21 22 23]
  [24 25 26]]]
[[ 0 12 24]
 [ 1 13 25]
 [ 2 14 26]]
'''
print()









發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章