numpy之多維數(shù)組的創(chuàng)建全過程
numpy多維數(shù)組的創(chuàng)建
多維數(shù)組(矩陣ndarray)
ndarray的基本屬性
shape
維度的大小ndim
維度的個(gè)數(shù)dtype
數(shù)據(jù)類型
1.1 隨機(jī)抽樣創(chuàng)建
1.1.1 rand
生成指定維度的隨機(jī)多維度浮點(diǎn)型數(shù)組,區(qū)間范圍是[0,1)
Random values in a given shape. Create an array of the given shape and populate it with random samples from a uniform distribution over ``[0, 1)``. nd1 = np.random.rand(1,1) print(nd1) print('維度的個(gè)數(shù)',nd1.ndim) print('維度的大小',nd1.shape) print('數(shù)據(jù)類型',nd1.dtype) # float 64
1.1.2 uniform
def uniform(low=0.0, high=1.0, size=None): # real signature unknown; restored from __doc__ """ uniform(low=0.0, high=1.0, size=None) Draw samples from a uniform distribution. Samples are uniformly distributed over the half-open interval ``[low, high)`` (includes low, but excludes high). In other words, any value within the given interval is equally likely to be drawn by `uniform`. Parameters ---------- low : float or array_like of floats, optional Lower boundary of the output interval. All values generated will be greater than or equal to low. The default value is 0. high : float or array_like of floats Upper boundary of the output interval. All values generated will be less than high. The default value is 1.0. size : int or tuple of ints, optional Output shape. If the given shape is, e.g., ``(m, n, k)``, then ``m * n * k`` samples are drawn. If size is ``None`` (default), a single value is returned if ``low`` and ``high`` are both scalars. Otherwise, ``np.broadcast(low, high).size`` samples are drawn. Returns ------- out : ndarray or scalar Drawn samples from the parameterized uniform distribution. See Also -------- randint : Discrete uniform distribution, yielding integers. random_integers : Discrete uniform distribution over the closed interval ``[low, high]``. random_sample : Floats uniformly distributed over ``[0, 1)``. random : Alias for `random_sample`. rand : Convenience function that accepts dimensions as input, e.g., ``rand(2,2)`` would generate a 2-by-2 array of floats, uniformly distributed over ``[0, 1)``. Notes ----- The probability density function of the uniform distribution is .. math:: p(x) = \frac{1}{b - a} anywhere within the interval ``[a, b)``, and zero elsewhere. When ``high`` == ``low``, values of ``low`` will be returned. If ``high`` < ``low``, the results are officially undefined and may eventually raise an error, i.e. do not rely on this function to behave when passed arguments satisfying that inequality condition. Examples -------- Draw samples from the distribution: >>> s = np.random.uniform(-1,0,1000) All values are within the given interval: >>> np.all(s >= -1) True >>> np.all(s < 0) True Display the histogram of the samples, along with the probability density function: >>> import matplotlib.pyplot as plt >>> count, bins, ignored = plt.hist(s, 15, density=True) >>> plt.plot(bins, np.ones_like(bins), linewidth=2, color='r') >>> plt.show() """ pass
nd2 = np.random.uniform(-1,5,size = (2,3)) print(nd2) print('維度的個(gè)數(shù)',nd2.ndim) print('維度的大小',nd2.shape) print('數(shù)據(jù)類型',nd2.dtype)
運(yùn)行結(jié)果:
1.1.3 randint
def randint(low, high=None, size=None, dtype='l'): # real signature unknown; restored from __doc__ """ randint(low, high=None, size=None, dtype='l') Return random integers from `low` (inclusive) to `high` (exclusive). Return random integers from the "discrete uniform" distribution of the specified dtype in the "half-open" interval [`low`, `high`). If `high` is None (the default), then results are from [0, `low`). Parameters ---------- low : int Lowest (signed) integer to be drawn from the distribution (unless ``high=None``, in which case this parameter is one above the *highest* such integer). high : int, optional If provided, one above the largest (signed) integer to be drawn from the distribution (see above for behavior if ``high=None``). size : int or tuple of ints, optional Output shape. If the given shape is, e.g., ``(m, n, k)``, then ``m * n * k`` samples are drawn. Default is None, in which case a single value is returned. dtype : dtype, optional Desired dtype of the result. All dtypes are determined by their name, i.e., 'int64', 'int', etc, so byteorder is not available and a specific precision may have different C types depending on the platform. The default value is 'np.int'. .. versionadded:: 1.11.0 Returns ------- out : int or ndarray of ints `size`-shaped array of random integers from the appropriate distribution, or a single such random int if `size` not provided. See Also -------- random.random_integers : similar to `randint`, only for the closed interval [`low`, `high`], and 1 is the lowest value if `high` is omitted. In particular, this other one is the one to use to generate uniformly distributed discrete non-integers. Examples -------- >>> np.random.randint(2, size=10) array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0]) >>> np.random.randint(1, size=10) array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) Generate a 2 x 4 array of ints between 0 and 4, inclusive: >>> np.random.randint(5, size=(2, 4)) array([[4, 0, 2, 1], [3, 2, 2, 0]]) """ pass
nd3 = np.random.randint(1,20,size=(3,4)) print(nd3) print('維度的個(gè)數(shù)',nd3.ndim) print('維度的大小',nd3.shape) print('數(shù)據(jù)類型',nd3.dtype) 展示: [[11 17 5 6] [17 1 12 2] [13 9 10 16]] 維度的個(gè)數(shù) 2 維度的大小 (3, 4) 數(shù)據(jù)類型 int32
注意點(diǎn):
1、如果沒有指定最大值,只是指定了最小值,范圍是[0,最小值)
2、如果有最小值,也有最大值,范圍為[最小值,最大值)
1.2 序列創(chuàng)建
1.2.1 array
通過列表進(jìn)行創(chuàng)建 nd4 = np.array([1,2,3]) 展示: [1 2 3] 通過列表嵌套列表創(chuàng)建 nd5 = np.array([[1,2,3],[4,5]]) 展示: [list([1, 2, 3]) list([4, 5])] 綜合 nd4 = np.array([1,2,3]) print(nd4) print(nd4.ndim) print(nd4.shape) print(nd4.dtype) nd5 = np.array([[1,2,3],[4,5,6]]) print(nd5) print(nd5.ndim) print(nd5.shape) print(nd5.dtype) 展示: [1 2 3] 1 (3,) int32 [[1 2 3] [4 5 6]] 2 (2, 3) int32
1.2.2 zeros
nd6 = np.zeros((4,4)) print(nd6) 展示: [[0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.]] 注意點(diǎn): 1、創(chuàng)建的數(shù)里面的數(shù)據(jù)為0 2、默認(rèn)的數(shù)據(jù)類型是float 3、可以指定其他的數(shù)據(jù)類型
1.2.3 ones
nd7 = np.ones((4,4)) print(nd7) 展示: [[1. 1. 1. 1.] [1. 1. 1. 1.] [1. 1. 1. 1.] [1. 1. 1. 1.]]
1.2.4 arange
nd8 = np.arange(10) print(nd8) nd9 = np.arange(1,10) print(nd9) nd10 = np.arange(1,10,2) print(nd10)
結(jié)果:
[0 1 2 3 4 5 6 7 8 9]
[1 2 3 4 5 6 7 8 9]
[1 3 5 7 9]
注意點(diǎn):
- 1、只填寫一位數(shù),范圍:[0,填寫的數(shù)字)
- 2、填寫兩位,范圍:[最低位,最高位)
- 3、填寫三位,填寫的是(最低位,最高位,步長)
- 4、創(chuàng)建的是一位數(shù)組
- 5、等同于np.array(range())
1.3 數(shù)組重新排列
nd11 = np.arange(10) print(nd11) nd12 = nd11.reshape(2,5) print(nd12) print(nd11) 展示: [0 1 2 3 4 5 6 7 8 9] [[0 1 2 3 4] [5 6 7 8 9]] [0 1 2 3 4 5 6 7 8 9] 注意點(diǎn): 1、有返回值,返回新的數(shù)組,原始數(shù)組不受影響 2、進(jìn)行維度大小的設(shè)置過程中,要注意數(shù)據(jù)的個(gè)數(shù),注意元素的個(gè)數(shù) nd13 = np.arange(10) print(nd13) nd14 = np.random.shuffle(nd13) print(nd14) print(nd13) 展示: [0 1 2 3 4 5 6 7 8 9] None [8 2 6 7 9 3 5 1 0 4] 注意點(diǎn): 1、在原始數(shù)據(jù)集上做的操作 2、將原始數(shù)組的元素進(jìn)行重新排列,打亂順序 3、shuffle這個(gè)是沒有返回值的
兩個(gè)可以配合使用,先打亂,在重新排列
1.4 數(shù)據(jù)類型的轉(zhuǎn)換
nd15 = np.arange(10,dtype=np.int64) print(nd15) nd16 = nd15.astype(np.float64) print(nd16) print(nd15) 展示: [0 1 2 3 4 5 6 7 8 9] [0. 1. 2. 3. 4. 5. 6. 7. 8. 9.] [0 1 2 3 4 5 6 7 8 9] 注意點(diǎn): 1、astype()不在原始數(shù)組做操作,有返回值,返回的是更改數(shù)據(jù)類型的新數(shù)組 2、在創(chuàng)建新數(shù)組的過程中,有dtype參數(shù)進(jìn)行指定
1.5 數(shù)組轉(zhuǎn)列表
arr1 = np.arange(10) # 數(shù)組轉(zhuǎn)列表 print(list(arr1)) print(arr1.tolist()) 展示: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
numpy 多維數(shù)組相關(guān)問題
創(chuàng)建(多維)數(shù)組
x = np.zeros(shape=[10, 1000, 1000], dtype='int')
得到全零的多維數(shù)組。
數(shù)組賦值
x[*,*,*] = ***
np數(shù)組保存
np.save("./**.npy",x)
讀取np數(shù)組
x = np.load("path")
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python類中__init__()?和self的詳細(xì)解析
self和__init__的語法學(xué)過Python的都清楚,但是靠死記硬背來迫使自己理解并不是個(gè)好辦法,下面這篇文章主要給大家介紹了關(guān)于Python類中__init__()?和self的相關(guān)資料,需要的朋友可以參考下2022-12-12python爬蟲入門教程--HTML文本的解析庫BeautifulSoup(四)
Beautiful Soup是python的一個(gè)庫,最主要的功能是從網(wǎng)頁抓取數(shù)據(jù)。下面這篇文章主要給大家介紹了python爬蟲之HTML文本的解析庫BeautifulSoup的相關(guān)資料,文中介紹的非常詳細(xì),對大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起看看吧。2017-05-05Python實(shí)現(xiàn)自動(dòng)整理文件的示例代碼
在我們?nèi)粘I钪?,文件總是雜亂無章的,這個(gè)時(shí)候就需要我們整理一下。但是文件太多的話整理起來是非常麻煩的,因此我們今天就來用Python實(shí)現(xiàn)文件的自動(dòng)整理2022-08-08Python基于Logistic回歸建模計(jì)算某銀行在降低貸款拖欠率的數(shù)據(jù)示例
這篇文章主要介紹了Python基于Logistic回歸建模計(jì)算某銀行在降低貸款拖欠率的數(shù)據(jù),結(jié)合實(shí)例形式分析了Python基于邏輯回歸模型的數(shù)值運(yùn)算相關(guān)操作技巧,需要的朋友可以參考下2019-01-01對python中的try、except、finally 執(zhí)行順序詳解
今天小編就為大家分享一篇對python中的try、except、finally 執(zhí)行順序詳解,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-02-02flask操作數(shù)據(jù)庫相關(guān)配置及實(shí)現(xiàn)示例步驟全解
這篇文章主要介紹了flask操作數(shù)據(jù)庫相關(guān)配置及實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01Python解決多進(jìn)程間訪問效率低的方法總結(jié)
這篇文章主要為大家詳細(xì)介紹了當(dāng)Python多進(jìn)程間訪問效率低時(shí),應(yīng)該如何解決?文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2022-09-09