numpy 基礎

數據分析經常使用的第三方庫python

numpy:數值計算數組

matplotlib:數據可視化數據結構

scipy:科學計算機app

pandas:時間和日期序列ide

1 numpy的基本特色

1)矢量化運算;將包含多個數據的集合做爲一個總體參與運算性能

2)成爲幾乎全部於數值分析、科學計算以及人工智能有關的功能模塊的底層模塊學習

3)性能卓越,運行速度快,絕大部分代碼用標準C語言甚至有彙編語言編寫編碼

4)數據集合中的元素必須同質,犧牲靈活性換取高性能;注,列表元組裏的元素能夠不一樣,但C裏面的數組元素必須同質人工智能

2 numpy數組

2.1 基本描述

numpy的數組是numpy.ndarray類型(n dimension array 意味n維數組)的對象,用於表示任意維度的數據結構,其維度信息經過shape屬性訪問spa

該對象由兩部分組成

A)實際數據:數組元素自己(在內存裏爲一行連續的數據)

B)元數據:對實際數據類型、結構等信息的描述

 

好比

元素據多是以下表示方式

base

A    B

 C

實際的MRO列表爲:MRO = [C A B base Object]

有時會出現實際數據是同樣的,可是元數據是不同的。

注:大部分針對數組的操做實際上僅僅是針對其元數據的操做,以此提高性能。

numpy.arange(start, stop, step, dtype),得到一個數組形式序列,注:包含起始值,但不包含終止值

numpy.array(p_object, dtype, copy, order, subok, ndim):得到一個包含給定元素的數組對象,注:只要可迭代對象便可

p_object:Union[ndarray, lterable, int, float]

dtype:Optional[object] = None 元素類型

copy:Optional[bool] = True

order:Optional[str] = "K"

subok:Optional[object] = False

ndim:Optional[int] = 0

可簡化爲

numpy.array([元素1,元素2,...]):參數能夠時同質的列表,元組,數組,注:元素之間的類型徹底一致,可是元素內部能夠由多個類型構成。

d = np.array([
    [np.arange(1, 5), np.arange(5, 9), np.arange(9, 13)],
    [np.arange(13, 17), np.arange(17, 21), np.arange(21, 25)]])
print(d.shape, d, sep='\n')

運行

(2, 3, 4)
[[[ 1  2  3  4]
  [ 5  6  7  8]
  [ 9 10 11 12]]

 [[13 14 15 16]
  [17 18 19 20]
  [21 22 23 24]]]

注意:

    # # 一維數組
    one_dim = np.arange(1,5)
    print(one_dim) # [1 2 3 4] 數據之間沒有逗號,而數組的元素之間是用逗號隔開的
    print(type(one_dim)) #<class 'numpy.ndarray'>類對象
    print(one_dim.dtype) #int32元素的類型,這個數據類型在python中是沒有定義的,是numpy庫本身定義的
    print(one_dim.shape) #(4,)表示4個元素

    # 二維數組
    two_dim = np.array([
        [1,2,3,3],
        [4,5,6,6],
        [7,8,9,9]],dtype=float) #float64  [[1. 2. 3. 3.]
    print(two_dim)  #
    print(type(two_dim))  # <class 'numpy.ndarray'>類對象
    print(two_dim.dtype)  # int32元素的類型,這個數據類型在python中是沒有定義的,是numpy庫本身定義的
    print(two_dim.shape) # (3,4)表示3行4列

    two1_dim = np.array([
        [1],
        [4],
        [7]])
    print(two1_dim)  #
    print(two1_dim.shape) # (3,1)表示3行1列

 

    # 三維數組
    three_dim = np.array([
        [
            np.arange(1,5),
            np.arange(5,9),
            np.arange(9,13)
        ],
        [
            np.arange(13,17),
            np.arange(17,21),
            np.arange(21,25),
        ],
        [
            np.arange(14, 18),
            np.arange(18, 22),
            np.arange(22, 26),
        ]])
    print(three_dim)  #
    print(type(three_dim))  # <class 'numpy.ndarray'>類對象
    print(three_dim.dtype)  # int32元素的類型,這個數據類型在python中是沒有定義的,是numpy庫本身定義的
    print(three_dim.shape) # (3, 3, 4),3頁,3行,4列
    print(three_dim[1,0,0])

 

2.2 數組下標

numpy中的數組也能夠採用下標訪問,其下標也是從0開始

import numpy as np
a = np.array([[[1, 2],
               [3, 4]],
              [[5, 6],
               [7, 8]]])
print(a)
print('a[0]:',a[0],sep='\n') 
print('a[0][0]:', a[0][0])          # a[0][0]: [1 2]
print('a[0][0][0]:', a[0][0][0])    #a[0][0][0]: 1

運行

[[[1 2]
  [3 4]]

 [[5 6]
  [7 8]]]
a[0]: [[
1 2] [3 4]]
a[0][0]: [
1 2]
a[0][0][0]:
1

深入理解shape屬性

import numpy as np
a = np.array([[[1, 2],
               [3, 4]],
              [[5, 6],
               [7, 8]]])

print(a.shape) #a.shape 結果爲(2,2,2)的元組
for i in range(a.shape[0]): #得到a.shape[0]元組中的第1個元素 2
    for j in range(a.shape[1]): #得到a.shape[1]元組中的第2個元素 2
        for k in range(a.shape[2]): #得到a.shape[2]元組中的第3個元素 2
            print(a[i][j][k], a[i, j, k]) #說明a[i][j][k]與a[i, j, k]等價,取出列表中的每個元素

經過len 或 numpy.ndarray.size獲取元素個數;

對於一維數組,size和len是相等的,

對於高維數組,len返回的是第一維的維數,而size返回的是全部維數的乘積。

import numpy as np
a = np.array([
    [
        [1, 2],
        [3, 4]
    ],
    [
        [5, 6],
        [7, 8]
    ]
])
print("a.shape:",a.shape) #(2, 2, 2)
print('a.size:',a.size) #8
print('a.ndim:',a.ndim) #3
print("len(a):",len(a)) #2

b = np.array([[
    [
        [1, 2],
        [3, 4]
    ],
    [
        [5, 6],
        [7, 8]
    ],
    [
        [9, 10],
        [11, 12]
    ]
]])
print("b.shape:",b.shape) #(1, 3, 2, 2)
print('b.size:',b.size) #12 元素個數,b.shape元組中全部元素的乘積
print('b.ndim:',b.ndim) #4 維度,至關於b.shape元組的長度,len(b.shape)
print("len(b):",len(b)) #1 只算頁數,至關於b.shape[0]

注:爲了便於觀察,將a b的視圖寫法略做調整

2.3 維度的改變

數組的維度能夠在定義後再作適當調整,reshape 和 shape 。

第一種方法   reshape方法

reshape(新維度): 不改變數據,注意,reshape()只接受一個參數,當多個參數時能夠選用

import numpy as np

a = np.arange(1,9)
b = a.reshape((2,4))

print('a',a.shape,a,sep='\n') #(8,)  [1 2 3 4 5 6 7 8]
print('b',b.shape,b,sep='\n') #(2, 4)  [[1 2 3 4]
                                      # [5 6 7 8]]

具體能夠查看print(help(a.reshape)

第二種方法  shape屬性

shape = 新維度:這種方法直接修改了所操做

import numpy as np

a = np.arange(1, 9)
a.shape = (2, 4)   # 修改原數組自己
print('a', a.shape, a, sep='\n')  #(2, 4)  [[1 2 3 4]
                                        #   [5 6 7 8]]

 

2.4 數據類型

ndarray對象的dtype屬性反映了元素的數據類型,能夠經過該屬性讀取或修改數組元素的數據類型

Object(array).astype(新數據類型) -> 新數組對象

a = np.array([1,2,3,4,5])
print(a.dtype) #int32

當賦值時不添加數據類型時,numpy會自動匹配默認值

 

也能夠指定數據類型

a = np.array([1,2,3,4,5],dtype=np.int8)
print(a.dtype) #int8

 

也能夠經過astype對列表的數據類型進行修改

import numpy as np
a = np.array([1,2,3,4,5],dtype=np.int8)

b = a.astype(float)
print(b.dtype) # float64

c = a.astype(str)
print(c.dtype,c)  #<U4 ['1' '2' '3' '4' '5']

d = b.astype(str)
print(d.dtype,d)  #<U32 ['1.0' '2.0' '3.0' '4.0' '5.0']

 

dtype表達方式的多樣性

import numpy as np

a = np.array([1,2,3,4],dtype=np.int32)
b = np.array([1,2,3,4],"int32")
c = np.array([1,2,3,4],"i4")

print(a.shape,b.shape,c.shape) # (4,) (4,) (4,) 以上三個是等價的

註釋:dtype=np.int32 與 ‘int32’ 表達結果相同。「int32」 與 ‘i4’ 相同,參看數據類型

 2.5 數據類型

2.5.1 變長類型,長度

a = np.array(['a1b1c1'], dtype=(np.str_, 1))
print(a.dtype, a, a[0]) #<U1 ['a'] a

b = np.array(['a1b1c1'], dtype=(np.str_, 2))
print(b.dtype, b, b[0]) #<U2 ['a1'] a1

c = np.array(['a1b1c1'], dtype=(np.str_, 3))
print(c.dtype, c, c[0]) #<U3 ['a1b'] a1b

實例二

a = np.array([
    'hello, word !',
    'hello, python !'
], dtype=(np.str_, 14))  # <U14 unicode字符串14個,當不寫14時,默認值比最長的字符數大一些的值,好比該處默認值爲<U15
print(a)
print(a.dtype)  # >i4 dtype表示每個最小單元的數據類型

運行

['hello, word !' 'hello, python ']
<U14

 

2.5.2 定長類型,(維度)

a = np.array([(1, 2, 3, 4)], dtype=(np.int32, 4))  # 每一個元素類型是4個int32,若維度不一致則會報錯
print(a.dtype, a.shape) #int32 (1, 4)

說明:t = numpy.dtype((int,5))每一個元素都是由5個int組成的一維數組,將5個int當成一個總體,其實是二維數組

2.5.3 類型字符串1,類型字符串2,. . .

a = np.array([('1234',(1,2,3,4))],dtype='u4,4i4')
print(a) #[(1234, [1, 2, 3, 4])]

print(a.dtype) # [('f0', '<u4'), ('f1', '<i4', (4,))]
print(a.shape) # (1,) # 一維數組,元素之間必須同質,元素內部能夠由多個不一樣類型數據構成

print(a[0]['f0']) # 1234
print(a['f0']) # [1234]

print(a[0]['f1']) # [1 2 3 4]
print(a['f1']) # [[1 2 3 4]]
# 備註 f0 f1是默認的,能夠修改

 

當元素中由三個數據構成

a = np.array([('1234','abcd',(1,2,3,4))],dtype='u4,U4,4i4')

print(a) # [(1234, 'abcd', [1, 2, 3, 4])]

print(a.dtype) # [('f0', '<u4'), ('f1', '<U4'), ('f2', '<i4', (4,))]
print(a.shape) # (1,) # 一維數組,元素之間必須同質,元素內部能夠由多個不一樣類型數據構成

print(a[0]['f0']) # 1234
print(a['f0']) # [1234]

print(a[0]['f1']) # abcd
print(a['f1']) # ['abcd']

print(a[0]['f2']) # [1 2 3 4]
print(a['f2']) # [[1 2 3 4]]
 

T:(逗號分隔的多個類型字符串)

t = numpy.dtype('U14,i4')此表示由U14和i4組成的元素,數組中的每一個元素都是這個「組合類型」

T :[(子段名稱,類型,維度),(子段描述),()...]

t = numpy.dtype([('name',numpy.str_,14),('age',numpy.int32)])此等價於'U14,i4'

 

2.5.4 元素中數據名修改

a = np.array([('1234', (1, 2, 3, 4)), ('5678', (5, 6, 7, 8))],
             dtype={'names': ['fa', 'fb'], 'formats': ['U4', '4i4']})

print(a.shape) #(2,)
print(a.dtype) #[('fa', '<U4'), ('fb', '<i4', (4,))]

print(a[0]['fa']) #1234
print(a[0]['fb']) #[1 2 3 4]

print(a[1]['fa']) #5678
print(a[1]['fb']) #[5 6 7 8]

print(a['fa']) #['1234' '5678']
print(a['fb']) #[[1 2 3 4]
               # [5 6 7 8]]

2.5.5 [(字段名稱,字段類型,字段維度),...]

元素內部的數據構成

a = np.array([('1234', (1, 2, 3, 4))],
             dtype=[('fa', np.str_, 4), ('fb', np.int32, 4)])
print(a.dtype) #[('fa', '<U4'), ('fb', '<i4', (4,))]
print(a[0]['fa']) #1234
print(a[0]['fb']) #[1 2 3 4]

與下段代碼等價

b = np.array([('1234', (1, 2, 3, 4))],
             dtype=[('fa', 'U4'), ('fb', '4i4')])
print(b.dtype) #[('fa', '<U4'), ('fb', '<i4', (4,))]
print(b[0]['fa']) #1234
print(b[0]['fb']) #[1 2 3 4]

2.5.6 (基本類型,解釋類型)

 實例一

a = np.array([0x1234],
             dtype=('>u2',
                    {'names': ['lo', 'hi'],
                     'formats': ['u1', 'u1']}))

print('{:x} {:x} {:x}'.format(a[0], a['lo'][0], a['hi'][0])) #1234 12 34

實例二

m = np.array(['python'],
             dtype=('U6',
                    {'names': ['codes'],
                     'formats': ['6u4']}))
print(m) #['python']
print(m[0]) #python
print(m['codes'][0]) #[112 121 116 104 111 110]

 

 

a = np.array([('abc', 123), ('def', 456)], dtype='U14,i4')
print(a) #[('abc', 123) ('def', 456)]
print(a.dtype) #[('f0', '<U14'), ('f1', '<i4')]
print(a[0][0], a[0][1]) #abc 123

b = np.array(
    [('abc', 123), ('def', 456)],
    dtype=[('name', np.str_, 14), ('age', np.int32)]
)
print(b) #[('abc', 123) ('def', 456)]
print(b[0]['name'], b[0]['age']) #abc 123

 

3 展平

將任意維度轉成一維

3.1 a.ravel()

將a數組轉變爲一維視圖(僅是轉換了視圖輸出形式,其a數據的內部存儲形式不變)

a = np.array([
    [1, 2, 3],
    [4, 5, 6]])

b = a.ravel() 
print(b) #[1 2 3 4 5 6]
print(a)#[[1 2 3]
         #[4 5 6]]

a *= 10
print(a) #[[10 20 30]
          #[40 50 60]]
          
print(b) #[10 20 30 40 50 60]

3.2 flatten()

將a數組轉變爲一維副本(將a數組複製一份並以一維數組的方式保存到內存中)

a = np.array([
    [1, 2, 3],
    [4, 5, 6]])

b = a.flatten()  # c是a的一維副本
print(b) #[1 2 3 4 5 6]
print(a) #[[1 2 3]
          #[4 5 6]]

a *= 10
print(a) #[[10 20 30]
          #[40 50 60]]

print(b) #[1 2 3 4 5 6]

4 轉置

轉置視圖實現方式:

Array.transpose() :視圖轉置方法

Array.T:視圖轉置屬性

不管哪一種裝置形式,僅改變視圖形式,其內部不改變

a = np.arange(1, 9).reshape(2, 4)
print(a)
# [[1 2 3 4]
#  [5 6 7 8]]
b = a.transpose()
print(b)
# [[1 5]
#  [2 6]
#  [3 7]
#  [4 8]]
c = a.reshape(4, 2)
print(c)
# [[1 2]
#  [3 4]
#  [5 6]
#  [7 8]]
d = a.T
print(d)
# [[1 5]
#  [2 6]
#  [3 7]
#  [4 8]]
a *= 10
print(a, b, c, d, sep='\n')  # 都是視圖 略

注:至少是二維數組才支持轉置,一維數據不支持轉置,嚴格來說,一維數據不存在行,只有列

將一列裝置爲行有兩種方法,以下代碼所示

a = np.arange(1,5)
print(a) #[1 2 3 4]
b = np.array([a]).transpose() #將其構形成二維再進行轉置
print(b)
# [[1]
#  [2]
#  [3]
#  [4]]
c = a.reshape(-1,1) #這裏-1行表示任意行,1,表示一列,
print(c)
# [[1]
#  [2]
#  [3]
#  [4]]

 5 自定義數據類型

自定義的時候,能夠先用numpy.dtype(T)建立類型

a = numpy.array([...],dtype = T)
t
= numpy.dtype(T) a = numpy.array([...],dtype = t)

實例一

# python 或numpy的內置類型
t = numpy.dtype(int)
t = numpy.dtype(numpy.int32)

python的數據類型會將其轉化爲numpy數據類型

實例二

# 實例二 類型字符串
t = numpy.dtype('int')
t = numpy.dtype('int32')

5.1 類型字符編碼

t = numpy.dtype('>(2,3)4i4') 

這個表示爲:

> 大端字節序

(2,3) 維度,2行3列

4:份量數,也就是說2行3列數組中又存在一個一維數組,每一個數組中又4個元素,這4個元素中每一個元素爲4字節整型i,i4至關於int32 

i 份量類型 ,每一個份量是一個整型,

4 份量字節數,每一個整型佔據4個字節,每一個類型的字長

實例一:

    b = np.array([
        (((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,27,28), (29,30,31,32), (33,34,35,36)),
         ((37,38,39,40), (41,42,43,44), (45,46,47,48)))
    ],dtype = '>(2,3)4i4')
    # dtype = '>(2,3,4)i4'與dtype = '>(2,3)4i4'等價
    print(b)
    print(b.dtype) #>i4 dtype表示每個最小單元的數據類型

運行

[[[[ 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 27 28]
   [29 30 31 32]
   [33 34 35 36]]

  [[37 38 39 40]
   [41 42 43 44]
   [45 46 47 48]]]]
>i4

 6 改變維度的4種方式

1)視圖變維、2)複製變維、3)就地變維、4)視圖轉置

6.1 視圖變維

import numpy
a = numpy.arange(1,7)
b = a.reshape(2,3) #[[1 2 3]
                   # [4 5 6]]
# 能夠變回來
c = b.reshape(6) #[1,2,3,4,5,6]
d = b.ravel() #扁平化 [1,2,3,4,5,6]

6.2 複製變維

e = b.flatten() #扁平化數據,e複製了b數據,e 獨立於b存在

6.3 就地變維

 a.shape = (2,3) #把已有的數組更變爲新的數組類型

 shape爲a的屬性,此時a的數據結構形式就發生了變化

 數據是共享的,元數據是獨立的,元數據包含了數據,還包括有對數據的描述(數據結構)

 元數據,能夠簡單理解爲描述爲語言

 a.resize((3,2))#就地變維,形參只有一個,(2,3)是以元組形式傳參的,

6.4 視圖轉置

7 組合與拆分

垂直組合:vstack((上,下))
垂直分割:vsplit(數組,分割數)->子數組元組
水平組合:hstack((左,右))
水平分割:hsplit(數組,分割數)->子數組元組
深度組合:dstack((前,後))
深度分割:dsplit(數組,分割數)->子數組元組
行組合:row_stack((上,下))
列組合:column_stack((左,右))

7.1 垂直、水平、深度組合方式

垂直:v = numpy.vstack((u,d))

水平:h = numpy.hstack((l,r))

深度:d = numpy.dstack((a,b))  能夠理解爲沿垂直紙面的組合方式

import numpy as np

a = np.arange(1,10).reshape(3,3)
b = a * 10
print(a, b, sep='\n')
# a
# [[1 2 3]
#  [4 5 6]
#  [7 8 9]]

# b
# [[10 20 30]
#  [40 50 60]
#  [70 80 90]]
c = np.vstack((a,b))
print(c)
# [[ 1  2  3]
#  [ 4  5  6]
#  [ 7  8  9]
#  [10 20 30]
#  [40 50 60]
#  [70 80 90]]
d = np.hstack((a,b))
print(d)
# [[ 1  2  3 10 20 30]
#  [ 4  5  6 40 50 60]
#  [ 7  8  9 70 80 90]]
e = np.dstack((a,b))
print(e)
# [[[ 1 10]
#   [ 2 20]
#   [ 3 30]]
# 
#  [[ 4 40]
#   [ 5 50]
#   [ 6 60]]
# 
#  [[ 7 70]
#   [ 8 80]
#   [ 9 90]]]

7.2 行組合、列組合

行組合:r = np.row_stack((u,d))

列組合:c = np.column_stack((l,r))

行、列組合通常針對一維數組,

對於二維及二維以上數組,行組合和垂直組合效果同樣,列組合和水平組合效果同樣

# 行組合
r = np.row_stack((u,d))
# u [1 2 3]
# d [4 5 6]
# r [
#     [1 2 3]
#     [4 5 6]
# ]

# 列組合
c = np.column_stack((l,r))
# l [1 2 3]
# r [4 5 6]
# c [
#     [1 4]
#     [2 5]
#     [3 6]
# ]

7.3 垂直分割、水平分割、深度分割

1)垂直分割

u,d = numpy.vsplit(v,2)

u,m,d = numpy.vsplit(v,3)#分割的份數

2)水平分割

垂直分割、水平分割和垂直合併、水平合併是可逆的

l,m,r = numpy.hsplit(h,3)

3)深度分割

q,r = np.dsplit(e,2)
print(q,r,sep='\n')

 備註:深度分割和深度合併是不可逆操做;

能夠經過下段代碼將其還原

q = q.transpose()[0].transpose()
r = r.transpose()[0].transpose()
print(q,r,sep='\n')

學習代碼

import numpy as np

a = np.arange(11, 20).reshape(3, 3)
print('a')
print(a)
b = np.arange(21, 30).reshape(3, 3)
print(b)
c = np.arange(31, 40).reshape(3, 3)
print(c)
d = np.vstack((a, b, c))
print('d')
print(d)

# concatenate()方法能夠選擇方向進行合併
e = np.concatenate((a, b, c), axis=0)  # 沿(行軸)合併
print('e')
print(e)
f, g, h = np.vsplit(e, 3)
print('f,g,h')
print(f, g, h, sep='\n')

i = np.hstack((a, b, c))  # 水平組合
print('i')
print(i)
j = np.concatenate((a, b, c), axis=1)
print('j')
print(j)

k, l, m = np.hsplit(j, 3)
print('k')
print(k)
print('l')
print(l)
print('m')
print(m)

n = np.dstack((a, b))
print('n')
print(n)
o, p = np.dsplit(n, 2)
print('o')
print(o)
print('p')
print(p)
print('o.T[0].T, p.T[0].T')
print(o.T)
print(o.T[0].T, p.T[0].T, sep='\n')

q = np.arange(1, 4)
r = np.arange(4, 7)
s = np.arange(7, 10)
print('q, r, s')
print(q, r, s, sep='\n')
t = np.row_stack((q, r, s))
#t = np.vstack((q, r, s))
print('t')
print(t)

u = np.column_stack((q, r, s))
#u = np.hstack((q, r, s))
print('u')
print(u)
View Code

8 複數

import numpy as np

a = np.array([
    [1 + 1j, 2 + 4j, 3 + 7j],
    [11 + 11j, 12 + 14j, 13 + 17j],
    [21 + 21j, 22 + 24j, 23 + 27j],
])
print(a.dtype) # complex128

print(a.dtype.char) # D
print(a.dtype.str) # <c16
print(a.imag) #虛部數組
# [[ 1.  4.  7.]
#  [11. 14. 17.]
#  [21. 24. 27.]]
# 數字後面的點,表示浮點數
print('-----')
print(a.real) # 實部數組
# [[ 1.  2.  3.]
#  [11. 12. 13.]
#  [21. 22. 23.]]
print(a.T) #轉置
# [[ 1. +1.j 11.+11.j 21.+21.j]
#  [ 2. +4.j 12.+14.j 22.+24.j]
#  [ 3. +7.j 13.+17.j 23.+27.j]]

9 numpy.ndarray 類的屬性

1)dtype    元素類型
2)shape   維度 幾行幾列
3)ndim     數組維數,也能夠理解爲最外層的維度
4)size      元素個數,元素數len,若是一維size與len是相等的,當二維及以上時,則size僅表示列數,size行列式乘積

a [1 2 3]
len(a) -> 3
a.sise -> 3

b [
        [1 2 3],
        [4 5 6]
]
len(b) ->2
b.size ->6

5)itemsize 每一個元素的字節數

6)nbytes 數組的總字節數 = size * itemsize

7)T 轉置視圖
8)real 複數數組的實部視圖
9)image 複數數組的虛部視圖

10)flat 扁平迭代器
flat屬性將返回一個numpy.flatiter對象。扁平迭代器可讓咱們像遍歷一維數組同樣去遍歷任意的多維數組。(迭代器的計算是惰性的,節約內存)
11)tolist 轉化爲python列表 ,轉換以後能夠明顯看到其是用逗號分隔的
numpy.ndarray.tolist()-> 列表對象

import numpy as np

a = np.array(
    [
        (1 + 1j, 2 + 2j, 3 + 7j),
        (1 + 1j, 2 + 2j, 3 + 7j),
        (1 + 1j, 2 + 2j, 3 + 7j)

    ]
)
print(a)
# [[1.+1.j 2.+2.j 3.+7.j]
#  [1.+1.j 2.+2.j 3.+7.j]
#  [1.+1.j 2.+2.j 3.+7.j]]
print(type(a))
# <class 'numpy.ndarray'>
print(type(a[0]))
# <class 'numpy.ndarray'>
print(type(a[0][0]))
# <class 'numpy.complex128'>
print(a.dtype)
# complex128
print(a.dtype.type)
# <class 'numpy.complex128'>
print(a.dtype.str) #<c16 16 * 8 類型的字符串
print(a.dtype.char) # D <c16 16 * 8 類型的字符碼,類型的字符編碼
print(a.dtype.itemsize) # 16 表示dtype所描述的數據佔用多少字節 這裏面的16 與上一個16 以及128 都是一致的

print(a.ndim) #2
print(len(a),a.size) #3 9
# 若爲三位數組,則len()表示頁數,a.size則是頁數*行*列
print(a.itemsize) #16
print(a.nbytes) #144
print(a.T)
# [[1.+1.j 1.+1.j 1.+1.j]
#  [2.+2.j 2.+2.j 2.+2.j]
#  [3.+7.j 3.+7.j 3.+7.j]]
print(a.real, a.imag, sep='\n') #

print(a.flat)
# <numpy.flatiter object at 0x000001ED511EA310>
for item in a.flat:
    print(item)
# (1+1j)
# (2+2j)
# (3+7j)
# (1+1j)
# (2+2j)
# (3+7j)
# (1+1j)
# (2+2j)
# (3+7j)
print('*'*6)
# ******
print(a.flat[4]) #(2+2j)
print(a.flat[[1,3,5]])
# [2.+2.j 1.+1.j 3.+7.j]
a.flat[[2,4,6]] = 0 # 賦值
print(a)
# [[1.+1.j 2.+2.j 0.+0.j]
#  [1.+1.j 0.+0.j 3.+7.j]
#  [0.+0.j 2.+2.j 3.+7.j]]
b = a.tolist()
print(b)
# [[(1+1j), (2+2j), 0j], [(1+1j), 0j, (3+7j)], [0j, (2+2j), (3+7j)]]

 

print('flat')
for elem in a.flat:  # 性能最優
    print(elem)

print('ravel')
for elem in a.ravel():  # 性能居中
    print(elem)

print('flatten')
for elem in a.flatten():  # 性能最差
    print(elem)

 

相似的代碼

import numpy as np

a = np.array([
    [1 + 1j, 2 + 4j, 3 + 7j],
    [4 + 2j, 5 + 5j, 6 + 8j],
    [7 + 3j, 8 + 6j, 9 + 9j]])
print('a.dtype')
print(a.dtype)
print('a.dtype.char')
print(a.dtype.char)
print('a.dtype.str')
print(a.dtype.str)
print('a.dtype.name')
print(a.dtype.name)
print('a.shape')
print(a.shape)
print('a.ndim')
print(a.ndim)
print('a.size')
print(a.size)
print('a.itemsize')
print(a.itemsize)
print('a.nbytes')
print(a.nbytes)
print('a.real')
print(a.real)
print('a.imag')
print(a.imag)
print('a.T')
print(a.T)

print('flat')
for elem in a.flat:  # 性能最優
    print(elem)

print('ravel')
for elem in a.ravel():  # 性能居中
    print(elem)

print('flatten')
for elem in a.flatten():  # 性能最差
    print(elem)

b = a.tolist()
print('b')
print(b)
c = np.array(b)
print('c')
print(c)

d = []
for i in range(10):
    d.append(i)
print('d')
print(d)

e = np.array([], dtype=int)
for i in range(10):
    e = np.append(e, i)
print('e')
print(e)
View Code

 

 

a.append(i)a = np.append(a,i)鏈表是指針形式,在內存中的空間能夠不連續,經過指針形式進行聯繫數組,必須是一個整塊的空間,數組中的元素須要的是連續內存,若是內存不足,則會開闢或尋找一個新的空間,將原內容拷貝到新的空間,
相關文章
相關標籤/搜索