Python使用numpy模塊創(chuàng)建數(shù)組操作示例
本文實例講述了Python使用numpy模塊創(chuàng)建數(shù)組操作。分享給大家供大家參考,具體如下:
創(chuàng)建數(shù)組
創(chuàng)建ndarray
創(chuàng)建數(shù)組最簡單的方法就是使用array函數(shù)。它接收一切序列型的對象(包括其他數(shù)組),然后產(chǎn)生一個新的含有傳入數(shù)據(jù)的Numpy數(shù)組。
array函數(shù)創(chuàng)建數(shù)組
import numpy as np
ndarray1 = np.array([1, 2, 3, 4])
ndarray2 = np.array(list('abcdefg'))
ndarray3 = np.array([[11, 22, 33, 44], [10, 20, 30, 40]])
zeros和zeros_like創(chuàng)建數(shù)組
用于創(chuàng)建數(shù)組,數(shù)組元素默認(rèn)值是0. 注意:zeros_linke函數(shù)只是根據(jù)傳入的ndarray數(shù)組的shape來創(chuàng)建所有元素為0的數(shù)組,并不是拷貝源數(shù)組中的數(shù)據(jù).
ndarray4 = np.zeros(10)
ndarray5 = np.zeros((3, 3))
ndarray6 = np.zeros_like(ndarray5) # 按照 ndarray5 的shape創(chuàng)建數(shù)組
# 打印數(shù)組元素類型
print("以下為數(shù)組類型:")
print('ndarray4:', type(ndarray4))
print('ndarray5:', type(ndarray5))
print('ndarray6:', type(ndarray6))
print("-------------")
print("以下為數(shù)組元素類型:")
print('ndarray4:', ndarray4.dtype)
print('ndarray5:', ndarray5.dtype)
print('ndarray6:', ndarray6.dtype)
print("-------------")
print("以下為數(shù)組形狀:")
print('ndarray4:', ndarray4.shape)
print('ndarray5:', ndarray5.shape)
print('ndarray6:', ndarray6.shape)
ones和ones_like創(chuàng)建數(shù)組
用于創(chuàng)建所有元素都為1的數(shù)組.ones_like用法同zeros_like用法
#創(chuàng)建數(shù)組,元素默認(rèn)值是0 ndarray7 = np.ones(10) ndarray8 = np.ones((3, 3)) #修改元素的值 ndarray8[0][1] = 999 ndarray9 = np.ones_like(ndarray5) # 按照 ndarray5 的shape創(chuàng)建數(shù)組
empty和empty_like創(chuàng)建數(shù)組
用于創(chuàng)建空數(shù)組,空數(shù)據(jù)中的值并不為0,而是未初始化的隨機(jī)值.
ndarray10 = np.empty(5) ndarray11 = np.empty((2, 3)) ndarray12 = np.empty_like(ndarray11)
arange創(chuàng)建數(shù)組
arange函數(shù)是python內(nèi)置函數(shù)range函數(shù)的數(shù)組版本.
ndarray13 = np.arange(10) #產(chǎn)生0-9共10個元素
ndarray14 = np.arange(10, 20) #產(chǎn)生從10-19共10個元素
ndarray15 = np.arange(10, 20, 2) #產(chǎn)生10 12 14 16 18, 2為step 間隔為2
print('ndarray14的形狀:', ndarray14.shape) #ndarray15的長度
ndarray14.reshape((2, 5)) #將其形狀改變?yōu)?2, 5) 分2部分 每份5個
eys創(chuàng)建對角矩陣數(shù)組
該函數(shù)用于創(chuàng)建一個N*N的矩陣,對角線為1,其余為0.
ndarray16 = np.eye(5)
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)組操作技巧總結(jié)》、《Python數(shù)學(xué)運(yùn)算技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
python Tkinter實時顯示數(shù)據(jù)功能實現(xiàn)
這篇文章主要介紹了python Tkinter實時顯示數(shù)據(jù)功能實現(xiàn),本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-07-07
Python實現(xiàn)批量壓縮解壓文件(zip、rar)
Python是一種廣泛使用的編程語言,非常適合處理各種任務(wù),包括批量解壓縮文件,本文主要介紹了Python實現(xiàn)批量壓縮解壓文件,具有一定的參考價值,感興趣的可以了解一下2023-09-09
Python編程functools模塊創(chuàng)建修改的高階函數(shù)解析
本篇文章主要為大家介紹functools模塊中用于創(chuàng)建、修改函數(shù)的高階函數(shù),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2021-09-09

