網站首頁 編程語言 正文
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
相關推薦
- 2023-10-16 nginx啟動與配置
- 2022-10-11 兩臺主機的vmware虛擬機相互連通的實現步驟_VMware
- 2022-08-12 Go?內聯優化讓程序員愛不釋手_Golang
- 2023-05-14 windows下vscode環境c++利用matplotlibcpp繪圖_C 語言
- 2022-12-12 C#中TextBox的橫線樣式及占位提示詳解_C#教程
- 2023-03-22 swift依賴注入和依賴注入容器詳解_Swift
- 2024-01-08 Request請求轉發和Response重定向
- 2023-03-28 Python使用機器學習模型實現溫度預測詳解_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支