ndarray数组
import numpy as np
ary = np.array([1, 2, 3, 4, 5, 6])
print(ary, type(ary))
print(ary.shape)
ary.shape = (2, 3)
print(ary, ary.shape)
ary.shape = (6,)
print(ary * 3)
print(ary > 3)
print(ary - ary)
ndarray在内存中存储:元数据+实际数据
优点:将实际数据与元数据分开存放,一方面提高内存空间的使用效率;另一方面减少对实际数据的访问频率,提高性能。
- 元数据:存储对目标数组的描述信息,比如dim(维数),size(元素个数),shape(维度),dtype(实际存储的数据类型)…
- 实际数据:完整的数组数据
ndarray数组的创建
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(a, 'size:', a.size, 'length:', len(a))
b = np.arange(0, 5, 1)
print(b)
c = np.arange(0, 36, 2)
print(c)
c.shape = (3, 2, 3)
print(c)
"""
[[[ 0 2 4]
[ 6 8 10]]
[[12 14 16]
[18 20 22]]
[[24 26 28]
[30 32 34]]]
"""
print(c[0])
print(c[0][1])
print(c[0][1][2])
d = np.zeros(3, dtype=float)
print(d, d.dtype)
d = d.astype(int)
print(d, d.dtype)
e = np.ones(3, bool)
print(e)
Numpy基本数据类型
类型名 | 类型表示符 |
---|
布尔型 | bool |
有符号整数型 | int8(-128~127)/int16/int32 |
无符号整数型 | uint8(0~255)/uint16/uint32 |
浮点型 | float16/float32/float64 |
复数型 | complex64/complex128 |
字串型 | str,每个字符用32位Unicode编码表示 |
自定义符合类型
类型字符码简写
类型 | 字符码 |
---|
bool | ? |
int8/16/32/64 | i1/i2/i4/i8 |
uint8/16/32/64 | u1/u2/u4/u8 |
float16/32/64 | f2/f4/f8 |
complex64/128 | c8/c16 |
str | U<字符数> |
datetime64 | M8[Y]/[M]/[D]/[h]/[m]/[s] |
字节序前缀:用于多字节整数和字符串
存储复合类型
import numpy as np
data = [
('one', [90, 80, 70], 11),
('two', [95, 85, 75], 12),
('three', [100, 100, 100], 13)
]
students_one = np.array(data, dtype='U5,3int32,int32')
print(students_one)
students_two = np.array(data, dtype=[('name', 'str', 5),
('score', 'int32', 3),
('age', 'int32')])
print('name=', students_two[2]['name'], 'age=', students_two[2]['age'])
students_three = np.array(data, dtype={'names': ['name', 'score', 'age'],
'formats': ['U5', '3int32', 'int32']})
print(students_three[1]['score'])
students_four = np.array(data, dtype={'names': ('U5', 0),
'scores': ('3int32', 20),
'ages': ('int32', 32)})
print(students_four)
times = ['2000-12-25', '2000', '2000-12',
'2012-01-01', '2022-02-22 22:22:22']
date = np.array(times)
print(date, date.dtype)
date = date.astype('M8[D]')
print(date, date.dtype)
print(date[0] - date[2])
数组对象的维度操作
import numpy as np
a = np.arange(1, 10)
print(a, a.shape)
b = a.reshape(3, 3)
print(a, '→a')
a[0] = 999
print(b, '→b')
print(b.ravel())
c = b.flatten()
print(c, '→c')
b[0][0] = 888
print(a, '→a')
print(b, '→b')
print(c, '→c')
c.shape = (3, 3)
print(c, '→c')
c.resize((9,))
print(c, '→c')
ndarray数组切片:数组对象[起始位置:终止位置:步长,…]
import numpy as np
a = np.arange(1, 10)
print(a)
print(a[:3])
print(a[3:6])
print(a[6:])
print(a[::-1])
print(a[:-4:-1])
print(a[-7::-1])
print(a[::])
print(a[:])
print(a[2::3])
a.resize(3, 3)
print(a[:2, :2])
print(a[1::2, ::2])
ndarray数组的掩码操作
import numpy as np
a = np.arange(1, 10)
mask = [True, False, True, False, True, False, True, False, True]
print(a[mask])
a = np.arange(100)
print(a[(a % 3 == 0)&(a % 7 == 0)])
test = np.array(['second', 'fourth', 'fifth', 'first', 'third'])
rank = [3, 0, 4, 1, 2]
print(test[rank])
多维数组的组合与拆分
水平方向上的操作
import numpy as np
a = np.arange(1, 7).reshape(2, 3)
b = np.arange(7, 13).reshape(2, 3)
print(a, '→a')
print(b, '→b')
c = np.hstack((a, b))
print(c, '→c')
a, b, c = np.hsplit(c, 3)
print(a, '→a')
print(b, '→b')
print(c, '→c')
垂直方向上的操作
import numpy as np
c = np.vstack((a, b))
print(c, '→c')
a, b = np.vsplit(c, 2)
print(a, '→a')
print(b, '→b')
深度方向上的操作
import numpy as np
c = np.dstack((a, b))
print(c, '→c')
a, b = np.dsplit(c, 2)
print(a, '→a')
print(b, '→b')
相关函数
import numpy as np
np.concatenate((a, b), axis=?)
np.spilt(c,2,axis=?)
a = np.array([1, 2, 3, 4, 5])
b = np.array([1, 2, 3])
b = np.pad(b, pad_width=(0, 2), mode='constant',
constant_values=-1)
print(b)
简单的一维数组组合方式
import numpy as np
a = np.arange(1, 6)
b = np.arange(6, 11)
c = np.row_stack((a, b))
print(c)
d = np.column_stack((a, b))
print(d)
ndarray类的其他属性
- shape: 维度
- dtype: 元素类型
- size: 元素数量
- ndim: 维数,len(shape)
- itemsize: 元素字节数
- nbytes: 总字节数=size*itemsize
- real: 复数数组的实部数组
- imag: 复数数组的虚部数组
- T: 数组对象的转置视图
- flat: 扁平迭代器
import numpy as np
a = np.array([[1 + 1j, 2 + 4j, 3 + 7j],
[4 + 2j, 5 + 5j, 6 + 8j],
[7 + 3j, 8 + 6j, 9 + 9j]])
print(a.shape)
print(a.dtype)
print(a.ndim)
print(a.size)
print(a.itemsize)
print(a.nbytes)
print(a.real, a.imag, sep='\n')
print(a.T)
print([elem for elem in a.flat])