欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python Numpy中ndarray的常見操作

 更新時(shí)間:2022年07月26日 15:22:27   作者:亦嵐君  
這篇文章主要介紹了Python Numpy中ndarray的常見操作,NumPy是Python的一種開源的數(shù)值計(jì)算擴(kuò)展,更多詳細(xì)內(nèi)容需要的朋友可以參考一下

前言

NumPy(Numerical Python)是Python的一種開源的數(shù)值計(jì)算擴(kuò)展。這種工具可用來存儲(chǔ)和處理大型矩陣,比Python自身的嵌套列表(nested list structure)結(jié)構(gòu)要高效的多(該結(jié)構(gòu)也可以用來表示矩陣(matrix)),支持大量的維度數(shù)組與矩陣運(yùn)算,此外也針對(duì)數(shù)組運(yùn)算提供大量的數(shù)學(xué)函數(shù)庫。
Numpy中主要使用ndarray來處理N維數(shù)組,Numpy中的大部分屬性和方法都是為ndarray服務(wù)的,所以掌握Numpy中ndarray的常見操作非常有必要!

0 Numpy基礎(chǔ)知識(shí)

NumPy的主要對(duì)象是同構(gòu)多維數(shù)組。它是一個(gè)元素表(通常是數(shù)字),所有類型都相同,由非負(fù)整數(shù)元組索引。在NumPy維度中稱為軸 。
下面所示的例子中,數(shù)組有2個(gè)軸。第一軸的長度為2,第二軸的長度為3。

[[ 1., 0., 0.],
 [ 0., 1., 2.]]

1 ndarray的屬性

1.1 輸出ndarray的常見屬性

  • ndarray.ndim : 數(shù)組的軸(維度)的個(gè)數(shù)。在Python世界中,維度的數(shù)量被稱為rank。
  • ndarray.shape :數(shù)組的維度。這是一個(gè)整數(shù)的元組,表示每個(gè)維度中數(shù)組的大小。對(duì)于有 n 行和 m 列的矩陣,shape 將是 (n,m)。因此,shape 元組的長度就是rank或維度的個(gè)數(shù) ndim。
  • ndarray.size :數(shù)組元素的總數(shù)。這等于 shape 的元素的乘積。
  • ndarray.dtype :一個(gè)描述數(shù)組中元素類型的對(duì)象??梢允褂脴?biāo)準(zhǔn)的Python類型創(chuàng)建或指定dtype。另外NumPy提供它自己的類型。例如numpy.int32、numpy.int16和numpy.float64。
  • ndarray.itemsize :數(shù)組中每個(gè)元素的字節(jié)大小。例如,元素為 float64 類型的數(shù)組的 itemsize 為8(=64/8),而 complex32 類型的數(shù)組的 itemsize 為4(=32/8)。它等于 ndarray.dtype.itemsize 。
>>> import numpy as np
>>> a = np.arange(15).reshape(3, 5)
>>> a
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])
>>> a.shape
(3, 5)
>>> a.ndim
2
>>> a.dtype.name
'int64'
>>> a.itemsize
8
>>> a.size
15
>>> type(a)
<type 'numpy.ndarray'>
>>> b = np.array([6, 7, 8])
>>> b
array([6, 7, 8])
>>> type(b)
<type 'numpy.ndarray'>

2 ndarray的數(shù)據(jù)類型

在同一個(gè)ndarray中,存儲(chǔ)的是同一類型的數(shù)據(jù),ndarray常見的數(shù)據(jù)類型包括:

3 修改ndarray的形狀和數(shù)據(jù)類型

3.1 查看和修改ndarray的形狀

## ndarray reshape操作
array_a = np.array([[1, 2, 3], [4, 5, 6]])
print(array_a, array_a.shape)
array_a_1 = array_a.reshape((3, 2))
print(array_a_1, array_a_1.shape)
# note: reshape不能改變ndarray中元素的個(gè)數(shù),例如reshape之前為(2,3),reshape之后為(3,2)/(1,6)...
## ndarray轉(zhuǎn)置
array_a_2 = array_a.T
print(array_a_2, array_a_2.shape)
## ndarray ravel操作:將ndarray展平
a.ravel()  # returns the array, flattened
array([ 1,  2,  3,  4,  5,  6 ])

輸出:
[[1 2 3]
 [4 5 6]] (2, 3)
[[1 2]
 [3 4]
 [5 6]] (3, 2)
[[1 4]
 [2 5]
 [3 6]] (3, 2)

3.2 查看和修改ndarray的數(shù)據(jù)類型

astype(dtype[, order, casting, subok, copy]):修改ndarray中的數(shù)據(jù)類型。傳入需要修改的數(shù)據(jù)類型,其他關(guān)鍵字參數(shù)可以不關(guān)注。

array_a = np.array([[1, 2, 3], [4, 5, 6]])
print(array_a, array_a.dtype)
array_a_1 = array_a.astype(np.int64)
print(array_a_1, array_a_1.dtype)
輸出:
[[1 2 3]
 [4 5 6]] int32
[[1 2 3]
 [4 5 6]] int64

4 ndarray數(shù)組創(chuàng)建

NumPy主要通過np.array()函數(shù)來創(chuàng)建ndarray數(shù)組。

>>> import numpy as np
>>> a = np.array([2,3,4])
>>> a
array([2, 3, 4])
>>> a.dtype
dtype('int64')
>>> b = np.array([1.2, 3.5, 5.1])
>>> b.dtype
dtype('float64')

也可以在創(chuàng)建時(shí)顯式指定數(shù)組的類型:

>>> c = np.array( [ [1,2], [3,4] ], dtype=complex )
>>> c
array([[ 1.+0.j,  2.+0.j],
       [ 3.+0.j,  4.+0.j]])

也可以通過使用np.random.random函數(shù)來創(chuàng)建隨機(jī)的ndarray數(shù)組。

>>> a = np.random.random((2,3))
>>> a
array([[ 0.18626021,  0.34556073,  0.39676747],
       [ 0.53881673,  0.41919451,  0.6852195 ]])

通常,數(shù)組的元素最初是未知的,但它的大小是已知的。因此,NumPy提供了幾個(gè)函數(shù)來創(chuàng)建具有初始占位符內(nèi)容的數(shù)組。這就減少了數(shù)組增長的必要,因?yàn)閿?shù)組增長的操作花費(fèi)很大。
函數(shù)zeros創(chuàng)建一個(gè)由0組成的數(shù)組,函數(shù) ones創(chuàng)建一個(gè)完整的數(shù)組,函數(shù)empty 創(chuàng)建一個(gè)數(shù)組,其初始內(nèi)容是隨機(jī)的,取決于內(nèi)存的狀態(tài)。默認(rèn)情況下,創(chuàng)建的數(shù)組的dtype是 float64 類型的。

>>> np.zeros( (3,4) )
array([[ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])
>>> np.ones( (2,3,4), dtype=np.int16 )                # dtype can also be specified
array([[[ 1, 1, 1, 1],
        [ 1, 1, 1, 1],
        [ 1, 1, 1, 1]],
       [[ 1, 1, 1, 1],
        [ 1, 1, 1, 1],
        [ 1, 1, 1, 1]]], dtype=int16)
>>> np.empty( (2,3) )                                 # uninitialized, output may vary
array([[  3.73603959e-262,   6.02658058e-154,   6.55490914e-260],
       [  5.30498948e-313,   3.14673309e-307,   1.00000000e+000]])

為了創(chuàng)建數(shù)字組成的數(shù)組,NumPy提供了一個(gè)類似于range的函數(shù),該函數(shù)返回?cái)?shù)組而不是列表。

>>> np.arange( 10, 30, 5 )
array([10, 15, 20, 25])
>>> np.arange( 0, 2, 0.3 )                 # it accepts float arguments
array([ 0. ,  0.3,  0.6,  0.9,  1.2,  1.5,  1.8])

5 ndarray數(shù)組的常見運(yùn)算

與許多矩陣語言不同,乘積運(yùn)算符*在NumPy數(shù)組中按元素進(jìn)行運(yùn)算。矩陣乘積可以使用@運(yùn)算符(在python> = 3.5中)或dot函數(shù)或方法執(zhí)行:

>>> A = np.array( [[1,1],
...             [0,1]] )
>>> B = np.array( [[2,0],
...             [3,4]] )
>>> A * B                       # elementwise product
array([[2, 0],
       [0, 4]])
>>> A @ B                       # matrix product
array([[5, 4],
       [3, 4]])
>>> A.dot(B)                    # another matrix product
array([[5, 4],
       [3, 4]])

某些操作(例如+=*=)會(huì)更直接更改被操作的矩陣數(shù)組而不會(huì)創(chuàng)建新矩陣數(shù)組。

>>> a = np.ones((2,3), dtype=int)
>>> b = np.random.random((2,3))
>>> a *= 3
>>> a
array([[3, 3, 3],
       [3, 3, 3]])
>>> b += a
>>> b
array([[ 3.417022  ,  3.72032449,  3.00011437],
       [ 3.30233257,  3.14675589,  3.09233859]])
>>> a += b                  # b is not automatically converted to integer type
Traceback (most recent call last):
  ...
TypeError: Cannot cast ufunc add output from dtype('float64') to dtype('int64') with casting rule 'same_kind'

當(dāng)使用不同類型的數(shù)組進(jìn)行操作時(shí),結(jié)果數(shù)組的類型對(duì)應(yīng)于更一般或更精確的數(shù)組(稱為向上轉(zhuǎn)換的行為)。

>>> a = np.ones(3, dtype=np.int32)
>>> b = np.linspace(0,pi,3)
>>> b.dtype.name
'float64'
>>> c = a+b
>>> c
array([ 1.        ,  2.57079633,  4.14159265])
>>> c.dtype.name
'float64'
>>> d = np.exp(c*1j)
>>> d
array([ 0.54030231+0.84147098j, -0.84147098+0.54030231j,
       -0.54030231-0.84147098j])
>>> d.dtype.name
'complex128'

許多一元操作,例如計(jì)算數(shù)組中所有元素的總和,都是作為ndarray類的方法實(shí)現(xiàn)的。

>>> a = np.random.random((2,3))
>>> a
array([[ 0.18626021,  0.34556073,  0.39676747],
       [ 0.53881673,  0.41919451,  0.6852195 ]])
>>> a.sum()
2.5718191614547998
>>> a.min()
0.1862602113776709
>>> a.max()
0.6852195003967595

默認(rèn)情況下,這些操作適用于數(shù)組,就像它是一個(gè)數(shù)字列表一樣,無論其形狀如何。但是,通過指定axis 參數(shù),您可以沿?cái)?shù)組的指定軸應(yīng)用操作:

>>> b = np.arange(12).reshape(3,4)
>>> b
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>>
>>> b.sum(axis=0)                            # 計(jì)算每一列的和
array([12, 15, 18, 21])
>>>
>>> b.min(axis=1)                            # 計(jì)算每一行的和
array([0, 4, 8])
>>>
>>> b.cumsum(axis=1)                         # cumulative sum along each row
array([[ 0,  1,  3,  6],
       [ 4,  9, 15, 22],
       [ 8, 17, 27, 38]])
解釋:以第一行為例,0=0,1=1+0,3=2+1+0,6=3+2+1+0

6 ndarray數(shù)組的索引、切片和迭代

一維的數(shù)組可以進(jìn)行索引、切片和迭代操作的,就像列表和其他Python序列類型一樣。

>>> a = np.arange(10)**3
>>> a
array([  0,   1,   8,  27,  64, 125, 216, 343, 512, 729])
>>> a[2]
8
>>> a[2:5]
array([ 8, 27, 64])
>>> a[:6:2] = -1000    # 等價(jià)于 a[0:6:2] = -1000; 從0到6的位置, 每隔一個(gè)設(shè)置為-1000
>>> a
array([-1000,     1, -1000,    27, -1000,   125,  fan 216,   343,   512,   729])
>>> a[ : :-1]                                 # 將a反轉(zhuǎn)
array([  729,   512,   343,   216,   125, -1000,    27, -1000,     1, -1000])

多維的數(shù)組每個(gè)軸可以有一個(gè)索引。這些索引以逗號(hào)??分隔的元組給出:

>>> b
array([[ 0,  1,  2,  3],
       [10, 11, 12, 13],
       [20, 21, 22, 23],
       [30, 31, 32, 33],
       [40, 41, 42, 43]])
>>> b[2,3]
23
>>> b[0:5, 1]                       # each row in the second column of b
array([ 1, 11, 21, 31, 41])
>>> b[ : ,1]                        # equivalent to the previous example
array([ 1, 11, 21, 31, 41])
>>> b[1:3, : ]                      # each column in the second and third row of b
array([[10, 11, 12, 13],
       [20, 21, 22, 23]])
>>> b[-1]                                  # the last row. Equivalent to b[-1,:]
array([40, 41, 42, 43])

7 ndarray數(shù)組的堆疊、拆分

幾個(gè)數(shù)組可以沿不同的軸堆疊在一起,例如:np.vstack()函數(shù)和np.hstack()函數(shù)

>>> a = np.floor(10*np.random.random((2,2)))
>>> a
array([[ 8.,  8.],
       [ 0.,  0.]])
>>> b = np.floor(10*np.random.random((2,2)))
>>> b
array([[ 1.,  8.],
       [ 0.,  4.]])
>>> np.vstack((a,b))
array([[ 8.,  8.],
       [ 0.,  0.],
       [ 1.,  8.],
       [ 0.,  4.]])
>>> np.hstack((a,b))
array([[ 8.,  8.,  1.,  8.],
       [ 0.,  0.,  0.,  4.]])

column_stack()函數(shù)將1D數(shù)組作為列堆疊到2D數(shù)組中。

>>> from numpy import newaxis
>>> a = np.array([4.,2.])
>>> b = np.array([3.,8.])
>>> np.column_stack((a,b))     # returns a 2D array
array([[ 4., 3.],
       [ 2., 8.]])
>>> np.hstack((a,b))           # the result is different
array([ 4., 2., 3., 8.])
>>> a[:,newaxis]               # this allows to have a 2D columns vector
array([[ 4.],
       [ 2.]])
>>> np.column_stack((a[:,newaxis],b[:,newaxis]))
array([[ 4.,  3.],
       [ 2.,  8.]])
>>> np.hstack((a[:,newaxis],b[:,newaxis]))   # the result is the same
array([[ 4.,  3.],
       [ 2.,  8.]])

使用hsplit(),可以沿?cái)?shù)組的水平軸拆分?jǐn)?shù)組,方法是指定要返回的形狀相等的數(shù)組的數(shù)量,或者指定應(yīng)該在其之后進(jìn)行分割的列:
同理,使用vsplit(),可以沿?cái)?shù)組的垂直軸拆分?jǐn)?shù)組,方法同上。

################### np.hsplit ###################
>>> a = np.floor(10*np.random.random((2,12)))
>>> a
array([[ 9.,  5.,  6.,  3.,  6.,  8.,  0.,  7.,  9.,  7.,  2.,  7.],
       [ 1.,  4.,  9.,  2.,  2.,  1.,  0.,  6.,  2.,  2.,  4.,  0.]])
>>> np.hsplit(a,3)   # Split a into 3
[array([[ 9.,  5.,  6.,  3.],
       [ 1.,  4.,  9.,  2.]]), array([[ 6.,  8.,  0.,  7.],
       [ 2.,  1.,  0.,  6.]]), array([[ 9.,  7.,  2.,  7.],
       [ 2.,  2.,  4.,  0.]])]
>>> np.hsplit(a,(3,4))   # Split a after the third and the fourth column
[array([[ 9.,  5.,  6.],
       [ 1.,  4.,  9.]]), array([[ 3.],
       [ 2.]]), array([[ 6.,  8.,  0.,  7.,  9.,  7.,  2.,  7.],
       [ 2.,  1.,  0.,  6.,  2.,  2.,  4.,  0.]])]
>>> x = np.arange(8.0).reshape(2, 2, 2)
>>> x
array([[[0.,  1.],
        [2.,  3.]],
       [[4.,  5.],
        [6.,  7.]]])
################### np.vsplit ###################
>>> np.vsplit(x, 2)
[array([[[0., 1.],
        [2., 3.]]]), array([[[4., 5.],
        [6., 7.]]])]

到此這篇關(guān)于Python Numpy中ndarray的常見操作的文章就介紹到這了,更多相關(guān)Python ndarray操作內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python pymongo模塊用法示例

    Python pymongo模塊用法示例

    這篇文章主要介紹了Python pymongo模塊用法,結(jié)合實(shí)例形式分析了Python中pymongo模塊的安裝與簡(jiǎn)單使用相關(guān)操作技巧,需要的朋友可以參考下
    2018-03-03
  • 基于matlab?atan2函數(shù)解析

    基于matlab?atan2函數(shù)解析

    這篇文章主要介紹了matlab?atan2函數(shù)解析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • Python在線和離線安裝第三方庫的方法

    Python在線和離線安裝第三方庫的方法

    這篇文章主要介紹了Python在線和離線安裝第三方庫的方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-10-10
  • 如何將matlab數(shù)據(jù)導(dǎo)入到Python中使用

    如何將matlab數(shù)據(jù)導(dǎo)入到Python中使用

    這篇文章主要介紹了如何將matlab數(shù)據(jù)導(dǎo)入到Python中使用,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-12-12
  • Python中獲取對(duì)象信息的方法

    Python中獲取對(duì)象信息的方法

    這篇文章主要介紹了Python中獲取對(duì)象信息的方法,是Python學(xué)習(xí)當(dāng)中的基礎(chǔ)知識(shí),需要的朋友可以參考下
    2015-04-04
  • 卡爾曼濾波數(shù)據(jù)處理技巧通俗理解及python實(shí)現(xiàn)

    卡爾曼濾波數(shù)據(jù)處理技巧通俗理解及python實(shí)現(xiàn)

    這篇文章主要為大家介紹了卡爾曼濾波數(shù)據(jù)處理技巧的通俗理解及python實(shí)現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-05-05
  • python 模擬登陸github的示例

    python 模擬登陸github的示例

    這篇文章主要介紹了python 模擬登陸github的示例代碼,幫助大家更好的理解和學(xué)習(xí)python 爬蟲的相關(guān)知識(shí),感興趣的朋友可以了解下
    2020-12-12
  • python學(xué)生信息管理系統(tǒng)(完整版)

    python學(xué)生信息管理系統(tǒng)(完整版)

    這篇文章主要為大家詳細(xì)介紹了python學(xué)生信息管理系統(tǒng)的完整版本代碼,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-10-10
  • pytorch動(dòng)態(tài)網(wǎng)絡(luò)以及權(quán)重共享實(shí)例

    pytorch動(dòng)態(tài)網(wǎng)絡(luò)以及權(quán)重共享實(shí)例

    今天小編就為大家分享一篇pytorch動(dòng)態(tài)網(wǎng)絡(luò)以及權(quán)重共享實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-01-01
  • Python SMTP發(fā)送電子郵件的示例

    Python SMTP發(fā)送電子郵件的示例

    這篇文章主要介紹了Python SMTP發(fā)送電子郵件的示例,幫助大家更好的理解和使用python,感興趣的朋友可以了解下
    2020-09-09

最新評(píng)論