NumPy 數(shù)組創(chuàng)建

2021-11-06 17:33 更新

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

有幾種方法可以創(chuàng)建數(shù)組。

例如,可以使用array函數(shù)從常規(guī) Python 列表或元組創(chuàng)建數(shù)組。結(jié)果數(shù)組的類型是從序列中元素的類型推導(dǎo)出來(lái)的。

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

一個(gè)常見(jiàn)的錯(cuò)誤在于array使用多個(gè)參數(shù)調(diào)用,而不是提供單個(gè)序列作為參數(shù)。

  1. >>> a = np.array(1, 2, 3, 4) # WRONG
  2. Traceback (most recent call last):
  3. ...
  4. TypeError: array() takes from 1 to 2 positional arguments but 4 were given
  5. >>> a = np.array([1, 2, 3, 4]) # RIGHT

array?將序列的序列轉(zhuǎn)換為二維數(shù)組,將序列的序列的序列轉(zhuǎn)換為三維數(shù)組,依此類推。

  1. >>> b = np.array([(1.5, 2, 3), (4, 5, 6)])
  2. >>> b
  3. array([[1.5, 2. , 3. ],
  4. [4. , 5. , 6. ]])

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

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

通常,數(shù)組的元素最初是未知的,但其大小是已知的。因此,NumPy 提供了幾個(gè)函數(shù)來(lái)創(chuàng)建具有初始占位符內(nèi)容的數(shù)組。這些最大限度地減少了增長(zhǎng)陣列的必要性,這是一項(xiàng)昂貴的操作。

該函數(shù)zeros創(chuàng)建一個(gè)全零數(shù)組,該函數(shù)?ones創(chuàng)建一個(gè)全1數(shù)組,該函數(shù)empty?創(chuàng)建一個(gè)初始內(nèi)容隨機(jī)且取決于內(nèi)存狀態(tài)的數(shù)組。默認(rèn)情況下,創(chuàng)建的數(shù)組的 dtype 是?float64,但可以通過(guò)關(guān)鍵字參數(shù)指定dtype。

  1. >>> np.zeros((3, 4))
  2. array([[0., 0., 0., 0.],
  3. [0., 0., 0., 0.],
  4. [0., 0., 0., 0.]])
  5. >>> np.ones((2, 3, 4), dtype=np.int16)
  6. array([[[1, 1, 1, 1],
  7. [1, 1, 1, 1],
  8. [1, 1, 1, 1]],
  9. [[1, 1, 1, 1],
  10. [1, 1, 1, 1],
  11. [1, 1, 1, 1]]], dtype=int16)
  12. >>> np.empty((2, 3))
  13. array([[3.73603959e-262, 6.02658058e-154, 6.55490914e-260], # may vary
  14. [5.30498948e-313, 3.14673309e-307, 1.00000000e+000]])

為了創(chuàng)建數(shù)字序列,NumPy 提供了arange類似于 Python 內(nèi)置的函數(shù)range,但返回一個(gè)數(shù)組。

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

當(dāng)arange與浮點(diǎn)參數(shù)一起使用時(shí),由于浮點(diǎn)精度有限,通常無(wú)法預(yù)測(cè)獲得的元素?cái)?shù)量。出于這個(gè)原因,通常最好使用linspace接收我們想要的元素?cái)?shù)量作為參數(shù)的函數(shù),而不是步驟:

  1. >>> from numpy import pi
  2. >>> np.linspace(0, 2, 9) # 9 numbers from 0 to 2
  3. array([0. , 0.25, 0.5 , 0.75, 1. , 1.25, 1.5 , 1.75, 2. ])
  4. >>> x = np.linspace(0, 2 * pi, 100) # useful to evaluate function at lots of points
  5. >>> f = np.sin(x)
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)