日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Numpy中創建數組的9種方式小結_python

作者:Dream丶Killer ? 更新時間: 2022-05-02 編程語言

1、使用empty方法創建數組

該方式可以創建一個空數組,dtype可以指定隨機數的類型,否則隨機采用一種類型生成隨機數。

import numpy as np

dt = np.numpy([2, 2], dtype=int)

在這里插入圖片描述


?

2、使用array創建數組

使用array方法可以基于Python列表創建數組,在不設置dtype的情況下,從列表中自動推斷數據類型。

import numpy as np

dt = np.array([1, 2, 3, 4, 5])
print('數組:', dt)
print('數據類型:', dt.dtype)
dt = np.array([1, 2, 3, 4, 5], dtype='f8')    # 64位浮點數
print('數組:', dt)
print('數據類型:', dt.dtype)

在這里插入圖片描述

3、使用zeros/ones創建數組

調用zeros/ones方法會創建一個全為‘0’/‘1’值的數組,通常在數組元素位置,大小一致的情況下來生成臨時數組?!?’/‘1’充當占位符。

import numpy as np

dt = np.zeros([3, 5], dtype=int)
print('數組:', dt)
print('數據類型:', dt.dtype)
dt = np.ones([5, 3], dtype=float)
print('數組:', dt)
print('數據類型:', dt.dtype)

在這里插入圖片描述

4、使用arange創建數組

使用arange方法可以基于一個數據范圍來創建數組。

import numpy as np

dt = np.arange(10, 30, 5)
print('數組:', dt)
print('數據類型:', dt.dtype)

在這里插入圖片描述

5、使用linspace創建數組

linspace是基于一個范圍來構造數組,參數num是開始值和結束值之間需要創建多少個數值。
retstep會改變計算的輸出,返回一個元組,而元組的兩個元素分別是需要生成的數組和數組的步差值。

import numpy as np

dt = np.linspace(20, 30, num=5)
print('數組:', dt)
print('數據類型:', dt.dtype)
dt = np.linspace(20, 30, num=5, endpoint=False)
print('數組:', dt)
print('數據類型:', dt.dtype)
dt = np.linspace(20, 30, num=5, retstep=True)
print('元組:', dt)

在這里插入圖片描述

6、使用numpy.random.rand創建數組

很多情況下手動創建的數組往往不能滿足業務需求,因此需要創建隨機數組。

import numpy as np

dt = np.random.rand(10)
print('數組:', dt)
print('數據類型:', dt.dtype)

在這里插入圖片描述

7、使用numpy.random.randn創建數組

numpy.random.randn方法也是產生隨機數組的一種方式,并且它能產生符合正態分布的隨機數。

import numpy as np

dt = np.random.randn(3, 5)
print('數組:', dt)
print('數據類型:', dt.dtype)

在這里插入圖片描述

8、使用numpy.random.randint創建數組

在10和30之間產生隨機數,并從中取5個數值來構建數組。

import numpy as np

dt = np.random.randint(10, 30, 5)
print('數組:', dt)
print('數據類型:', dt.dtype)

在這里插入圖片描述

9、使用fromfunction創建數組

fromfunction方法可以通過一個函數規則來創建數組。該方法中shape參數制定了創建數組的規則,shape=(4,5),最終創建的結果就是4行5列的二維數組。

import numpy as np

dt = np.fromfunction(lambda i, j:i + j, (4, 5), dtype=int)
print('數組:', dt)
print('數據類型:', dt.dtype)

在這里插入圖片描述

原文鏈接:https://blog.csdn.net/qq_43965708/article/details/114288345

欄目分類
最近更新