Numpy學(xué)習(xí)
1.NumPy(Numerical Python) 是 Python 語言的一個(gè)擴(kuò)展程序庫咪橙,支持大量的維度數(shù)組與矩陣運(yùn)算睦疫,此外也針對(duì)數(shù)組運(yùn)算提供大量的數(shù)學(xué)函數(shù)庫碍彭。
2.NumPy 是一個(gè)運(yùn)行速度非呈旯澹快的數(shù)學(xué)庫羊瘩,主要用于數(shù)組計(jì)算俩檬,包含###
- 一個(gè)強(qiáng)大的N維數(shù)組對(duì)象 ndarray
- 廣播功能函數(shù)
- 整合 C/C++/Fortran 代碼的工具
- 線性代數(shù)、傅里葉變換纲熏、隨機(jī)數(shù)生成等功能
2.1 NumPy 數(shù)據(jù)類型
????numpy支持的數(shù)據(jù)類型比 Python 內(nèi)置的類型要多很多妆丘,基本上可以和 C 語言的數(shù)據(jù)類型對(duì)應(yīng)上,其中部分類型對(duì)應(yīng)為 Python 內(nèi)置的類型局劲。下表列舉了常用 NumPy 基本類型2.2 創(chuàng)建數(shù)據(jù)類型
numpy 的數(shù)值類型實(shí)際上是 dtype 對(duì)象的實(shí)例勺拣。
class dtype(object):
def __init__(self, obj, align=False, copy=False):
pass
每個(gè)內(nèi)建類型都有一個(gè)唯一定義它的字符代碼,如下:
a = np.dtype('b1')
print(a.type) # <class 'numpy.bool_'>
print(a.itemsize) # 1
a = np.dtype('i1')
print(a.type) # <class 'numpy.int8'>
print(a.itemsize) # 1
a = np.dtype('i2')
print(a.type) # <class 'numpy.int16'>
print(a.itemsize) # 2
a = np.dtype('i4')
print(a.type) # <class 'numpy.int32'>
print(a.itemsize) # 4
a = np.dtype('i8')
print(a.type) # <class 'numpy.int64'>
print(a.itemsize) # 8
a = np.dtype('u1')
print(a.type) # <class 'numpy.uint8'>
print(a.itemsize) # 1
a = np.dtype('u2')
print(a.type) # <class 'numpy.uint16'>
print(a.itemsize) # 2
a = np.dtype('u4')
print(a.type) # <class 'numpy.uint32'>
print(a.itemsize) # 4
a = np.dtype('u8')
print(a.type) # <class 'numpy.uint64'>
print(a.itemsize) # 8
a = np.dtype('f2')
print(a.type) # <class 'numpy.float16'>
print(a.itemsize) # 2
a = np.dtype('f4')
print(a.type) # <class 'numpy.float32'>
print(a.itemsize) # 4
a = np.dtype('f8')
print(a.type) # <class 'numpy.float64'>
print(a.itemsize) # 8
a = np.dtype('S')
print(a.type) # <class 'numpy.bytes_'>
print(a.itemsize) # 0
a = np.dtype('S3')
print(a.type) # <class 'numpy.bytes_'>
print(a.itemsize) # 3
a = np.dtype('U3')
print(a.type) # <class 'numpy.str_'>
print(a.itemsize) # 12
2.3數(shù)據(jù)類型信息
Python 的浮點(diǎn)數(shù)通常是64位浮點(diǎn)數(shù)容握,幾乎等同于 np.float64 宣脉。
NumPy和Python整數(shù)類型的行為在整數(shù)溢出方面存在顯著差異,與 NumPy 不同剔氏,Python 的 int 是靈活的塑猖。這意味著Python整數(shù)可以擴(kuò)展以容納任何整數(shù)并且不會(huì)溢出。
def __init__(self, int_type):
pass
def min(self):
pass
def max(self):
pass
例如:
ii16 = np.iinfo(np.int16)
print(ii16.min) # -32768
print(ii16.max) # 32767
ii32 = np.iinfo(np.int32)
print(ii32.min) # -2147483648
print(ii32.max) # 2147483647
2.4 numpy的數(shù)組類型
NumPy 數(shù)組的維數(shù)稱為秩(rank)绵载,秩就是軸的數(shù)量申尼,即數(shù)組的維度腹备,一維數(shù)組的秩為 1,二維數(shù)組的秩為 2蜡励,以此類推。
在 NumPy中阻桅,每一個(gè)線性的數(shù)組稱為是一個(gè)軸(axis)凉倚,也就是維度(dimensions)。比如說嫂沉,二維數(shù)組相當(dāng)于是兩個(gè)一維數(shù)組稽寒,其中第一個(gè)一維數(shù)組中每個(gè)元素又是一個(gè)一維數(shù)組。所以一維數(shù)組就是 NumPy 中的軸(axis)趟章,第一個(gè)軸相當(dāng)于是底層數(shù)組杏糙,第二個(gè)軸是底層數(shù)組里的數(shù)組。而軸的數(shù)量——秩蚓土,就是數(shù)組的維數(shù)宏侍。
很多時(shí)候可以聲明 axis。axis=0蜀漆,表示沿著第 0 軸進(jìn)行操作谅河,即對(duì)每一列進(jìn)行操作;axis=1确丢,表示沿著第1軸進(jìn)行操作绷耍,即對(duì)每一行進(jìn)行操作。
NumPy 的數(shù)組中比較重要 ndarray 對(duì)象屬性有:
##ndarray.ndim的應(yīng)用實(shí)例:
import numpy as np
a = np.arange(24)
print (a.ndim) # a 現(xiàn)只有一個(gè)維度
# 現(xiàn)在調(diào)整其大小
b = a.reshape(2,4,3) # b 現(xiàn)在擁有三個(gè)維度
print (b.ndim)
ndarray.shape,?ndarray.reshape都是用來調(diào)整數(shù)組的大小
ndarray.itemsize
ndarray.itemsize 以字節(jié)的形式返回?cái)?shù)組中每一個(gè)元素的大小蠕嫁。
例如锨天,一個(gè)元素類型為 float64 的數(shù)組 itemsiz 屬性值為 8(float64 占用 64 個(gè) bits,每個(gè)字節(jié)長(zhǎng)度為 8剃毒,所以 64/8病袄,占用 8 個(gè)字節(jié)),又如赘阀,一個(gè)元素類型為 complex32 的數(shù)組 item 屬性為 4(32/8)
import numpy as np
a = np.array([1],dtype = np.int8)
print(a.itemsize)
1
import numpy as np
a = np.array([1],dtype = np.float64)
print(a.itemsize)
8
ndarray.flags
a = np.array([1,2,3,4,5])
print (a.flags)
運(yùn)行結(jié)果:
C_CONTIGUOUS : True
F_CONTIGUOUS : True
OWNDATA : True
WRITEABLE : True
ALIGNED : True
WRITEBACKIFCOPY : False
UPDATEIFCOPY : False
Numpy創(chuàng)建數(shù)組
numpy.empty
numpy.empty 方法用來創(chuàng)建一個(gè)指定形狀(shape)益缠、數(shù)據(jù)類型(dtype)且未初始化的數(shù)組
numpy.empty(shape, dtype = float, order = 'C')
import numpy as np
a = np.empty([3,2],dtype = int)
print(a)
運(yùn)行結(jié)果:
[[1,2]
[3,4]
[5,6]]
注意 ? 數(shù)組元素為隨機(jī)值,因?yàn)樗鼈兾闯跏蓟?/strong>
numpy.zeros創(chuàng)建指定大小的數(shù)組基公,用0進(jìn)行填充
numpy.ones創(chuàng)建指定大小的數(shù)組幅慌,用1進(jìn)行填充
import numpy as np
# 默認(rèn)為浮點(diǎn)數(shù)
x = np.zeros(5)
print(x)
# 設(shè)置類型為整數(shù)
y = np.zeros((5,), dtype = np.int)
print(y)
# 自定義類型
z = np.zeros((2,2), dtype = [('x', 'i4'), ('y', 'i4')])
print(z)
輸出結(jié)果為:
[0. 0. 0. 0. 0.]
[0 0 0 0 0]
[[(0, 0) (0, 0)]
[(0, 0) (0, 0)]]
import numpy as np
# 默認(rèn)為浮點(diǎn)數(shù)
x = np.ones(5)
print(x)
# 自定義類型
x = np.ones([2,2], dtype = int)
print(x)
3. 時(shí)間日期和時(shí)間增量
3.1 datetime64 基礎(chǔ)
在 numpy 中,我們很方便的將字符串轉(zhuǎn)換成時(shí)間日期類型 datetime64 ( datetime 已被 python 包含的日期時(shí)間庫所占用)轰豆。
(1)從字符串創(chuàng)建 datetime64 類型時(shí)齿诞,默認(rèn)情況下,numpy 會(huì)根據(jù)字符串自動(dòng)選擇對(duì)應(yīng)的單位骂租。
import numpy as np
a = np.datetime64('2020-03-01')
print(a, a.dtype) # 2020-03-01 datetime64[D]
a = np.datetime64('2020-03')
print(a, a.dtype) # 2020-03 datetime64[M]
a = np.datetime64('2020-03-08 20:00:05')
print(a, a.dtype) # 2020-03-08T20:00:05 datetime64[s]
a = np.datetime64('2020-03-08 20:00')
print(a, a.dtype) # 2020-03-08T20:00 datetime64[m]
a = np.datetime64('2020-03-08 20')
print(a, a.dtype) # 2020-03-08T20 datetime64[h]
2020-03-01 datetime64[D]
2020-03 datetime64[M]
2020-03-08T20:00:05 datetime64[s]
2020-03-08T20:00 datetime64[m]
2020-03-08T20 datetime64[h]
(2)從字符串創(chuàng)建 datetime64 類型時(shí)祷杈,可以強(qiáng)制指定使用的單位。
import numpy as np
a = np.datetime64('2020-03','D')#寫3不行渗饮,必須寫03
print(a,a.dtype)
a = np.datetime64('2020-10','Y')
print(a,a.dtype)
print(np.datetime64('2020-03') == np.datetime64('2020-03-01'))
print(np.datetime64('2020-03') == np.datetime64('2020-03-02'))
2020-03-01 datetime64[D]
2020 datetime64[Y]
True
False
(3)從字符串創(chuàng)建 datetime64 數(shù)組時(shí)但汞,如果單位不統(tǒng)一,則一律轉(zhuǎn)化成其中最小的單位互站。
import numpy as np
a = np.array(['2020-03', '2020-03-08', '2020-03-08 20:00'], dtype='datetime64')
print(a, a.dtype)
?
['2020-03-01T00:00' '2020-03-08T00:00' '2020-03-08T20:00'] datetime64[m]
(4)使用 arange() 創(chuàng)建 datetime64 數(shù)組私蕾,用于生成日期范圍。
import numpy as np
a = np.arange('2020-08-01', '2020-08-10', dtype=np.datetime64)
print(a)
print(a.dtype)
結(jié)果:['2020-08-01' '2020-08-02' '2020-08-03' '2020-08-04' '2020-08-05'
'2020-08-06' '2020-08-07' '2020-08-08' '2020-08-09']
datetime64[D]
a = np.arange('2020-08-01 20:00', '2020-08-10', dtype=np.datetime64)
print(a)
print(a.dtype)
結(jié)果:['2020-08-01T20:00' '2020-08-01T20:01' '2020-08-01T20:02' ...
'2020-08-09T23:57' '2020-08-09T23:58' '2020-08-09T23:59']
datetime64[m]
a = np.arange('2020-05', '2020-12', dtype=np.datetime64)
print(a)
print(a.dtype)
結(jié)果:['2020-05' '2020-06' '2020-07' '2020-08' '2020-09' '2020-10' '2020-11']
datetime64[M]
3.2 datetime64 和 timedelta64 運(yùn)算
(1)timedelta64 表示兩個(gè) datetime64 之間的差胡桃。timedelta64 也是帶單位的踩叭,并且和相減運(yùn)算中的兩個(gè) datetime64 中的較小的單位保持一致。
import numpy as np
a = np.datetime64('2020-03-08') - np.datetime64('2020-03-07')
b = np.datetime64('2020-03-08') - np.datetime64('202-03-07 08:00')
c = np.datetime64('2020-03-08') - np.datetime64('2020-03-07 23:00', 'D')
print(a, a.dtype)
print(b, b.dtype)
?結(jié)果:
1 days timedelta64[D]
956178240 minutes timedelta64[m]
a = np.datetime64('2020-03') + np.timedelta64(20, 'D')
b = np.datetime64('2020-06-15 00:00') + np.timedelta64(12, 'h')
print(a, a.dtype)
print(b, b.dtype)
結(jié)果:
2020-03-21 datetime64[D]
2020-06-15T12:00 datetime64[m]
(2)生成 timedelta64時(shí)标捺,要注意年('Y')和月('M')這兩個(gè)單位無法和其它單位進(jìn)行運(yùn)算(一年有幾天懊纳?一個(gè)月有幾個(gè)小時(shí)?這些都是不確定的)
import numpy as np
a = np.timedelta64(1, 'Y')
b = np.timedelta64(a, 'M')
print(a)
print(b)
c = np.timedelta64(1, 'h')
d = np.timedelta64(c, 'm')
print(c) # 1 hours
print(d) # 60 minutes
?結(jié)果:
1 years
12 months
1 hours
60 minutes
print(np.timedelta64(a, 'D'))
print(np.timedelta64(b, 'D'))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-21-5a703214abd7> in <module>
----> 1 print(np.timedelta64(a, 'D'))
2
3 print(np.timedelta64(b, 'D'))
TypeError: Cannot cast NumPy timedelta64 scalar from metadata [Y] to [D] according to the rule 'same_kind'
(3)timedelta64 的運(yùn)算亡容。
import numpy as np
a = np.timedelta64(1, 'Y')
b = np.timedelta64(6, 'M')
c = np.timedelta64(1, 'W')
d = np.timedelta64(1, 'D')
e = np.timedelta64(10, 'D')
print(a) # 1 years
print(b) # 6 months
print(a + b) # 18 months
print(a - b) # 6 months
print(2 * a) # 2 years
print(a / b) # 2.0
f = c / d # 7.0
print(c % e) # 7 days
print(f.dtype)
??結(jié)果:
1 years
6 months
18 months
6 months
2 years
2.0
7 days
float64
(4)numpy.datetime64 與 datetime.datetime 相互轉(zhuǎn)換
import numpy as np
import datetime
dt = datetime.datetime(year=2020, month=10, day=23, hour=21, minute=55, second=30)
dt64 = np.datetime64(dt, 's')
print(dt64, dt64.dtype)
#astype()為轉(zhuǎn)換數(shù)據(jù)類型
dt2 = dt64.astype(datetime.datetime)
print(dt2, type(dt2))
2020-10-23T21:55:30 datetime64[s]
2020-10-23 21:55:30 <class 'datetime.datetime'>
3.3 datetime64 的應(yīng)用
- numpy.busday_offset(dates, offsets, roll='raise', weekmask='1111100', holidays=None, busdaycal=None, out=None) First adjusts the date to fall on a valid day according to the roll rule, then applies offsets to the given dates counted in valid days.
參數(shù) roll :{'raise', 'nat', 'forward', 'following', 'backward', 'preceding', 'modifiedfollowing', 'modifiedpreceding'}
- 'raise' means to raise an exception for an invalid day.
- 'nat' means to return a NaT (not-a-time) for an invalid day.
- 'forward' and 'following' mean to take the first valid day later in time.
- 'backward' and 'preceding' mean to take the first valid day earlier in time.
(1)將指定的偏移量應(yīng)用于工作日嗤疯,單位天('D')。計(jì)算下一個(gè)工作日闺兢,如果當(dāng)前日期為非工作日茂缚,默認(rèn)報(bào)錯(cuò)∥萏罚可以指定 forward 或backward 規(guī)則來避免報(bào)錯(cuò)脚囊。(一個(gè)是向前取第一個(gè)有效的工作日,一個(gè)是向后取第一個(gè)有效的工作日)
import numpy as np
a = np.busday_offset('2020-10-23', offsets=1)
print(a)
2020-10-26
a = np.busday_offset('2020-10-24', offsets=1)
print(a)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-31-2bd35d386423> in <module>
----> 1 a = np.busday_offset('2020-10-24', offsets=1)
2 print(a)
<__array_function__ internals> in busday_offset(*args, **kwargs)
ValueError: Non-business day date in busday_offset
----------------------------------------------------------------------------------------
a = np.busday_offset('2020-10-23', offsets=0, roll='forward')
b = np.busday_offset('2020-10-23', offsets=0, roll='backward')
print(a)
print(b)
2020-10-23
2020-10-23
a = np.busday_offset('2020-10-23', offsets=1, roll='forward')
b = np.busday_offset('2020-10-23', offsets=1, roll='backward')
print(a)
print(b)
2020-10-26
2020-10-26
可以指定偏移量為 0 來獲取當(dāng)前日期向前或向后最近的工作日桐磁,當(dāng)然悔耘,如果當(dāng)前日期本身就是工作日,則直接返回當(dāng)前日期我擂。
2. numpy.is_busday(dates, weekmask='1111100', holidays=None, busdaycal=None, out=None) Calculates which of the givendates are valid days, and which are not.
(1)返回指定日期是否是工作日衬以。
import numpy as np
# 2020-07-10 星期五
a = np.is_busday('2020-07-10')
b = np.is_busday('2020-07-11')
print(a) # True
print(b) # False
(2)統(tǒng)計(jì)一個(gè) datetime64[D] 數(shù)組中的工作日天數(shù)。
注.統(tǒng)計(jì)數(shù)據(jù)個(gè)數(shù)時(shí)校摩,采用的是左閉右開
import numpy as np
# 2020-10-23 星期五
begindates = np.datetime64('2020-10-23')
enddates = np.datetime64('2020-12-23')
#統(tǒng)計(jì)天數(shù)從2020-10-23到2020-12-23
a = np.arange(begindates, enddates, dtype='datetime64')
#統(tǒng)計(jì)有多少周內(nèi)日
b = np.count_nonzero(np.is_busday(a))
print(a)
print(b)
?
['2020-10-23' '2020-10-24' '2020-10-25' '2020-10-26' '2020-10-27'
'2020-10-28' '2020-10-29' '2020-10-30' '2020-10-31' '2020-11-01'
'2020-11-02' '2020-11-03' '2020-11-04' '2020-11-05' '2020-11-06'
'2020-11-07' '2020-11-08' '2020-11-09' '2020-11-10' '2020-11-11'
'2020-11-12' '2020-11-13' '2020-11-14' '2020-11-15' '2020-11-16'
'2020-11-17' '2020-11-18' '2020-11-19' '2020-11-20' '2020-11-21'
'2020-11-22' '2020-11-23' '2020-11-24' '2020-11-25' '2020-11-26'
'2020-11-27' '2020-11-28' '2020-11-29' '2020-11-30' '2020-12-01'
'2020-12-02' '2020-12-03' '2020-12-04' '2020-12-05' '2020-12-06'
'2020-12-07' '2020-12-08' '2020-12-09' '2020-12-10' '2020-12-11'
'2020-12-12' '2020-12-13' '2020-12-14' '2020-12-15' '2020-12-16'
'2020-12-17' '2020-12-18' '2020-12-19' '2020-12-20' '2020-12-21'
'2020-12-22']
43
(3)自定義周掩碼值看峻,即指定一周中哪些星期是工作日。
import numpy as np
# 2020-10-23 星期五
a = np.is_busday('2020-10-23', weekmask=[1, 1, 1, 1, 1, 0, 0])
b = np.is_busday('2020-10-23', weekmask=[1, 1, 1, 1, 0, 0, 1])
print(a)
print(b)
?
True
False
3. numpy.busday_count(begindates, enddates, weekmask='1111100', holidays=[], busdaycal=None, out=None) Counts the
number of valid days between begindates and enddates , not including the day of enddates .
(1)返回兩個(gè)日期之間的工作日數(shù)量衙吩。
import numpy as np
?
begindates = np.datetime64('2020-10-23')
enddates = np.datetime64('2021-01-01')
a = np.busday_count(begindates, enddates)
b = np.busday_count(enddates, begindates)
print(a)
print(b)
?
50
-50
4. 數(shù)組的創(chuàng)建
4.1 數(shù)組的創(chuàng)建
4.1 1. 依據(jù)現(xiàn)有數(shù)據(jù)來創(chuàng)建 ndarray
(a)通過array()函數(shù)進(jìn)行創(chuàng)建互妓。
import numpy as np
a = np.array([0, 1, 2, 3, 4])
b = np.array((0, 1, 2, 3, 4))
print(a, type(a))
print(b, type(b))
c = np.array([[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25],
[26, 27, 28, 29, 30],
[31, 32, 33, 34, 35]])
print(c, type(c))
d = np.array([[(1.5, 2, 3), (4, 5, 6)],
[(3, 2, 1), (4, 5, 6)]])
print(d, type(d))
[0 1 2 3 4] <class 'numpy.ndarray'>
[0 1 2 3 4] <class 'numpy.ndarray'>
[[11 12 13 14 15]
[16 17 18 19 20]
[21 22 23 24 25]
[26 27 28 29 30]
[31 32 33 34 35]] <class 'numpy.ndarray'>
[[[1.5 2. 3. ]
[4. 5. 6. ]]
[[3. 2. 1. ]
[4. 5. 6. ]]] <class 'numpy.ndarray'>
(b)通過asarray()函數(shù)進(jìn)行創(chuàng)建
array() 和 asarray() 都可以將結(jié)構(gòu)數(shù)據(jù)轉(zhuǎn)化為 ndarray,但是 array() 和 asarray() 主要區(qū)別就是當(dāng)數(shù)據(jù)源是ndarray 時(shí), array() 仍然會(huì) copy 出一個(gè)副本冯勉,占用新的內(nèi)存澈蚌,但不改變 dtype 時(shí) asarray() 不會(huì)。
import numpy as np
x = [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
y = np.array(x)
z = np.asarray(x)
x[1][2] = 2
print(x,type(x))
# [[1, 1, 1], [1, 1, 2], [1, 1, 1]] <class 'list'>
print(y,type(y))
# [[1 1 1]
# [1 1 1]
# [1 1 1]] <class 'numpy.ndarray'>
print(z,type(z))
# [[1 1 1]
# [1 1 1]
# [1 1 1]] <class 'numpy.ndarray'>
array() 和 asarray() 的區(qū)別珠闰。( array() 和 asarray() 主要區(qū)別就是當(dāng)數(shù)據(jù)源是ndarray 時(shí)惜浅, array() 仍然會(huì) copy 出一個(gè)副本瘫辩,占用新的內(nèi)存伏嗜,但不改變 dtype 時(shí) asarray() 不會(huì)。
import numpy as np
x = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]])
y = np.array(x)
z = np.asarray(x)
w = np.asarray(x, dtype=np.int)
x[1][2] = 2
print(x,type(x),x.dtype)
#[[1,1,1]
#[1,1,1]
#[1,1,1]]
print(y,type(y),y.dtype)
?
?
print(z,type(z),z.dtype)
print(w,type(w),w.dtype)
[[1 1 1]
[1 1 2]
[1 1 1]] <class 'numpy.ndarray'> int32
[[1 1 1]
[1 1 1]
[1 1 1]] <class 'numpy.ndarray'> int32
[[1 1 1]
[1 1 2]
[1 1 1]] <class 'numpy.ndarray'> int32
[[1 1 1]
[1 1 2]
[1 1 1]] <class 'numpy.ndarray'> int32
更改為較大的dtype時(shí)伐厌,其大小必須是array的最后一個(gè)axis的總大谐谐瘛(以字節(jié)為單位)的除數(shù)
4.1.3 (c)通過fromfunction()函數(shù)進(jìn)行創(chuàng)建
(1)給函數(shù)繪圖的時(shí)候可能會(huì)用到 fromfunction() ,該函數(shù)可從函數(shù)中創(chuàng)建數(shù)組挣轨。
def fromfunction(function, shape, **kwargs):
import numpy as np
def f(x, y):
return 10 * x + y
x = np.fromfunction(f, (5, 4), dtype=int)
print(x)
# [[ 0 1 2 3]
# [10 11 12 13]
# [20 21 22 23]
# [30 31 32 33]
# [40 41 42 43]]
x = np.fromfunction(lambda i, j: i == j, (3, 3), dtype=int)
print(x)
x = np.fromfunction(lambda i, j: i - j, (3, 3), dtype=int)
print(x)
x = np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int)
print(x)
[[ 0 1 2 3]
[10 11 12 13]
[20 21 22 23]
[30 31 32 33]
[40 41 42 43]]
[[ True False False]
[False True False]
[False False True]]
[[ 0 -1 -2]
[ 1 0 -1]
[ 2 1 0]]
[[0 1 2]
[1 2 3]
[2 3 4]]
4.2 2. 依據(jù) ones 和 zeros 填充方式
(a)零數(shù)組
- zeros() 函數(shù):返回給定形狀和類型的零數(shù)組军熏。
- zeros_like() 函數(shù):返回與給定數(shù)組形狀和類型相同的零數(shù)組。
def zeros(shape, dtype=None, order='C'):
def zeros_like(a, dtype=None, order='K', subok=True, shape=None):
x = np.zeros(5)
print(x) # [0. 0. 0. 0. 0.]
x = np.zeros([2, 3])
print(x)
# [[0. 0. 0.]
# [0. 0. 0.]]
x = np.array([[1, 2, 3], [4, 5, 6]])
y = np.zeros_like(x)
print(y)
?
[0. 0. 0. 0. 0.]
[[0. 0. 0.]
[0. 0. 0.]]
[[0 0 0]
[0 0 0]]
(b)1數(shù)組
- ones() 函數(shù):返回給定形狀和類型的1數(shù)組卷扮。
- ones_like() 函數(shù):返回與給定數(shù)組形狀和類型相同的1數(shù)組荡澎。
(c)空數(shù)組
- empty() 函數(shù):返回一個(gè)空數(shù)組,數(shù)組元素為隨機(jī)數(shù)晤锹。
- empty_like 函數(shù):返回與給定數(shù)組具有相同形狀和類型的新數(shù)組摩幔。
import numpy as np
x = np.empty(5)
print(x)
?
x = np.empty((3, 2))
print(x)
x = np.array([[1, 2, 3], [4, 5, 6]])
y = np.empty_like(x)
print(y)
?
[0. 0. 0. 0. 0.]
[[0. 0.]
[0. 0.]
[0. 0.]]
[[1127399952 609 0]
[ 0 1 1629516654]]
(d)單位數(shù)組
- eye() 函數(shù):返回一個(gè)對(duì)角線上為1,其它地方為零的單位數(shù)組鞭铆。
- identity() 函數(shù):返回一個(gè)方的單位數(shù)組或衡。
import numpy as np
x = np.eye(4)
print(x)
# [[1. 0. 0. 0.]
# [0. 1. 0. 0.]
# [0. 0. 1. 0.]
# [0. 0. 0. 1.]]
x = np.eye(2, 3)
print(x)
# [[1. 0. 0.]
# [0. 1. 0.]]
x = np.identity(4)
print(x)
# [[1. 0. 0. 0.]
# [0. 1. 0. 0.]
# [0. 0. 1. 0.]
# [0. 0. 0. 1.]]
?
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]
[[1. 0. 0.]
[0. 1. 0.]]
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]
(e)對(duì)角數(shù)組
- diag() 函數(shù):提取對(duì)角線或構(gòu)造對(duì)角數(shù)組。
import numpy as np
x = np.arange(9).reshape((3, 3))
print(x)
# [[0 1 2]
# [3 4 5]
# [6 7 8]]
print(np.diag(x)) # [0 4 8]
print(np.diag(x, k=1)) # [1 5]
print(np.diag(x, k=-1)) # [3 7]
v = [1, 3, 5, 7]
x = np.diag(v)
(f)常數(shù)數(shù)組
- full() 函數(shù):返回一個(gè)常數(shù)數(shù)組车遂。
- full_like() 函數(shù):返回與給定數(shù)組具有相同形狀和類型的常數(shù)數(shù)組封断。
import numpy as np
x = np.full((2,), 7)
print(x)
# [7 7]
x = np.full(2, 7)
print(x)
# [7 7]
x = np.full((2, 7), 7)
print(x)
# [[7 7 7 7 7 7 7]
# [7 7 7 7 7 7 7]]
x = np.array([[1, 2, 3], [4, 5, 6]])
y = np.full_like(x, 7)
print(y)
?
?
[7 7]
[7 7]
[[7 7 7 7 7 7 7]
[7 7 7 7 7 7 7]]
[[7 7 7]
[7 7 7]]