NumPy 核心和模塊
# 來(lái)源:NumPy Essentials ch4
步長(zhǎng)
# 步長(zhǎng)是每個(gè)維度相鄰兩個(gè)元素的偏移差值
import numpy as np
x = np.arange(8, dtype = np.int8)
x
# array([0, 1, 2, 3, 4, 5, 6, 7])
# x 是一維數(shù)組,步長(zhǎng)為 1城舞,因?yàn)?int8 占一個(gè)字節(jié)
x.strides
# (1,)
# data 屬性可以觀察原始數(shù)據(jù)
str(x.data)
# '\x00\x01\x02\x03\x04\x05\x06\x07'
# 將 x 轉(zhuǎn)換為 2x4 的二維數(shù)組
x.shape = 2, 4
x
'''
array([[0, 1, 2, 3],
[4, 5, 6, 7]], dtype=int8)
'''
# 第二維的步長(zhǎng)是 1夕晓,等于類型大小
# 第一維的步長(zhǎng)是 4,等于第二位步長(zhǎng)乘以第二維的長(zhǎng)度
x.strides
# (4, 1)
# 原始數(shù)據(jù)還是不變
str(x.data)
# '\x00\x01\x02\x03\x04\x05\x06\x07'
# 轉(zhuǎn)換為 1x4x2 的三位數(shù)組
x.shape = 1,4,2
# 第三維的步長(zhǎng)是 1,等于類型大小
# 第二維的步長(zhǎng)是 2灾炭,等于第三維步長(zhǎng)乘以第三維的長(zhǎng)度
# 第一維的步長(zhǎng)是 8,等于第二維步長(zhǎng)乘以第二維的長(zhǎng)度
x.strides
# (8, 2, 1)
str(x.data)
# '\x00\x01\x02\x03\x04\x05\x06\x07'
'''
對(duì)于連續(xù)數(shù)組(flags 中為連續(xù)):
strides[ndim - 1] = itemsize
strides[i] = strides[i + 1] * shape[i + 1]
def calc_strides(shape, itemsize):
ndim = len(shape)
strides = [0] * ndim
strides[-1] = itemsize
for i in xrange(ndim - 2, -1, -1):
strides[i] = strides[i + 1] * shape[i + 1]
return strides
'''
# 再來(lái)看看不連續(xù)數(shù)組
# 這里 x 是連續(xù)的泊业,y 是不連續(xù)的
x = np.ones((10000,))
y = np.ones((10000 * 100, ))[::100]
# 它們的形狀一樣,都是 10000 大小的一維數(shù)組
x.shape, y.shape
# ((10000,), (10000,))
# 值也一樣
x == y
# array([ True, True, True, ..., True, True, True], dtype=bool)
# 查看它們的標(biāo)識(shí)
x.flags
'''
C_CONTIGUOUS : True
F_CONTIGUOUS : True
OWNDATA : True
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
由于 x 是一維數(shù)組啊易,所以行和列都連續(xù)
'''
y.flags
'''
C_CONTIGUOUS : False
F_CONTIGUOUS : False
OWNDATA : False
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
y 是由切片產(chǎn)生的吁伺,所以行和列都不連續(xù)
并且沒(méi)有自己的數(shù)據(jù)
'''
# 它們的步長(zhǎng)是不一樣的
# 某個(gè)維度在切片時(shí)提供了步長(zhǎng)
# 數(shù)組的步長(zhǎng)也會(huì)乘這個(gè)數(shù)
x.strides, y.strides
# ((8,), (800,))
'''
不連續(xù)數(shù)組由于不是緩存友好的
訪問(wèn)也較慢
%timeit x.sum()
100000 loops, best of 3: 13.8 μs per loop
%timeit y.sum()
10000 loops, best of 3: 25.9 μs per loop
結(jié)構(gòu)化數(shù)組
# 結(jié)構(gòu)化數(shù)組也叫作記錄數(shù)組
# 它的元素是一條記錄
# 要?jiǎng)?chuàng)建這種數(shù)組,我們需要使用數(shù)組來(lái)表示數(shù)據(jù)租谈,每個(gè)元素是一個(gè)元組篮奄,表示記錄
# 然后我們需要指定類型,使用數(shù)組來(lái)表示割去,每個(gè)元素是個(gè)二元組
# 字段用二元組表示窟却,第一項(xiàng)是名稱,第二項(xiàng)是類型
x = np.array([(1, 0.5, 'NumPy'), (10, -0.5, 'Essential')],
dtype=[('f0', '<i4'), ('f1', '<f4'), ('f2', 'S10')])
# 位置下標(biāo)得到的是元組(記錄)
x[0]
# (1, 0.5, 'NumPy')
# 還可以通過(guò)字段名稱訪問(wèn)
# 得到的是字段值的數(shù)組
x['f2']
# array(['NumPy', 'Essential'], dtype='|S10')
# 字段值的數(shù)據(jù)還是視圖
# 修改它會(huì)修改原始數(shù)組
y = x['f0']
y
# array([ 1, 10])
y[:] = y * 10
y
# array([ 10, 100])
y[:] = y + 0.5
y
# array([ 10, 100])
x
'''
array([(10, 0.5, 'NumPy'), (100, -0.5, 'Essential')],
dtype=[('f0', '<i4'), ('f1', '<f4'), ('f2', 'S10')])
'''
# 字段的每個(gè)元素也可以是數(shù)組
z = np.ones((2,), dtype = ('3i4, (2,3)f4'))
z
'''
array([([1, 1, 1], [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]),
([1, 1, 1], [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]])],
dtype=[('f0', '<i4', (3,)), ('f1', '<f4', (2, 3))])
'''
# 我們也可以給字段類型重命名
x.dtype.names
# ('f0', 'f1', 'f2')
x.dtype.names = ('id', 'value', 'note')
x
'''
array([(10, 0.5, 'NumPy'), (100, -0.5, 'Essential')],
dtype=[('id', '<i4'), ('value', '<f4'), ('note', 'S10')])
'''
# 也可以使用字典來(lái)表示類型
# names 鍵是名稱列表呻逆,formats 鍵是類型列表
dict_ex = np.zeros((2,), dtype = {'names':['id', 'value'], 'formats':['i4', '2f4']})
dict_ex
'''
array([(0, [0.0, 0.0]), (0, [0.0, 0.0])],
dtype=[('id', '<i4'), ('value', '<f4', (2,))])
'''
# 屬性索引也支持多值
x[['id', 'note']]
'''
array([(10, 'NumPy'), (100, 'Essential')],
dtype=[('id', '<i4'), ('note', 'S10')])
'''
日期時(shí)間
# datetime64 可以使用字符串來(lái)構(gòu)造
x = np.datetime64('2015-04-01')
y = np.datetime64('2015-04')
x.dtype, y.dtype
# (dtype('<M8[D]'), dtype('<M8[M]'))
# 我們也可以指定最小單位
# 缺失的值會(huì)使用 1 來(lái)填充
y = np.datetime64('2015-04', 'D')
y, y.dtype
# (numpy.datetime64('2015-04-01'), dtype('<M8[D]'))
# 我們可以使用 arange 來(lái)生成日期數(shù)組
x = np.arange('2015-01', '2015-04', dtype = 'datetime64[M]')
x
# array(['2015-01', '2015-02', '2015-03'], dtype='datetime64[M]')
# 但是只包含日期單位時(shí)夸赫,不能指定時(shí)間單位
y = np.datetime64('2015-04-01', 's')
# TypeError: Cannot parse "2015-04-01" as unit 's' using casting rule 'same_kind'
# datetime64 相減會(huì)生成 timedelta64
x
# array(['2015-01', '2015-02', '2015-03'], dtype='datetime64[M]')
y = np.datetime64('2015-01-01')
x - y
# array([ 0, 31, 59], dtype='timedelta64[D]')
# 我們也可以將 datetime64 與 timedelta64 相加
# 這表示 2015 年 1 月 1 日加上 12 個(gè)月是 2016 年 1 月 1 日
np.datetime64('2015') + np.timedelta64(12, 'M')
# numpy.datetime64('2016-01')
# 或者 timedelta64 之間的運(yùn)算
# 這表示一周是 7 天
np.timedelta64(1, 'W') / np.timedelta64(1, 'D')
# 7.0
x
# array(['2015-01', '2015-02', '2015-03'], dtype='datetime64[M]')
# tolist 將 NumPy 數(shù)組轉(zhuǎn)換成 Python 列表
# 如果數(shù)組是 datetime64 類型
# 每個(gè)元素會(huì)轉(zhuǎn)為原生的 datetime.data
x.tolist()
'''
[datetime.date(2015, 1, 1),
datetime.date(2015, 2, 1),
datetime.date(2015, 3, 1)]
'''
# datetime64 的 item 方法會(huì)返回等價(jià)的 datetime.date 對(duì)象
[element.item() for element in x]
'''
[datetime.date(2015, 1, 1),
datetime.date(2015, 2, 1),
datetime.date(2015, 3, 1)]
'''
NumPy 文件 IO
# 首先創(chuàng)建記錄數(shù)組
id = np.arange(1000)
value = np.random.random(1000)
day = np.random.random_integers(0, 365, 1000) * np.timedelta64(1,'D')
date = np.datetime64('2014-01-01') + day
# np.core.records.fromarrays 從字段數(shù)組創(chuàng)建記錄數(shù)組
rec_array = np.core.records.fromarrays([id, value, date], names='id, value, date', formats='i4, f4, a10')
rec_array[:5]
'''
rec.array([(0, 0.07019801437854767, '2014-07-10'),
(1, 0.4863224923610687, '2014-12-03'),
(2, 0.9525277614593506, '2014-03-11'),
(3, 0.39706873893737793, '2014-01-02'),
(4, 0.8536589741706848, '2014-09-14')],
dtype=[('id', '<i4'), ('value', '<f4'), ('date', 'S10')])
'''
# savetxt 以純文本形式保存數(shù)組
# 將格式指定為逗號(hào)分隔,所以它是 CSV
np.savetxt('./record.csv', rec_array, fmt='%i,%.4f,%s')
# 我們需要將其讀進(jìn)來(lái)
# 并指定類型和分隔符
# 使用 np.loadtxt 也可以
read_array = np.genfromtxt('./record.csv', dtype='i4,f4,a10', delimiter=',', skip_header=0)
read_array[:5]
'''
array([(0, 0.07020000368356705, '2014-07-10'),
(1, 0.486299991607666, '2014-12-03'),
(2, 0.9524999856948853, '2014-03-11'),
(3, 0.3971000015735626, '2014-01-02'),
(4, 0.8536999821662903, '2014-09-14')],
dtype=[('f0', '<i4'), ('f1', '<f4'), ('f2', 'S10')])
'''
# 為字段重命名
read_array.dtype.names = ('id', 'value', 'date')
# 獲取 value 字段是否大于 0.75
mask = read_array['value'] >= 0.75
from numpy.lib.recfunctions import append_fields
# append_fields 添加新的字段
# 參數(shù)依次是源數(shù)組咖城、新字段名稱茬腿、數(shù)據(jù)和類型
read_array = append_fields(read_array, 'mask', data=mask, dtypes='i1')
read_array[:5]
'''
masked_array(data = [(0, 0.07020000368356705, '2014-07-10', 0)
(1, 0.486299991607666, '2014-12-03', 0)
(2, 0.9524999856948853, '2014-03-11', 1)
(3, 0.3971000015735626, '2014-01-02', 0)
dtype = [('id', '<i4'), ('value', '<f4'), ('date', 'S10'), ('mask','i1')])
'''