文章目录
-
- 对象
- 数据类型
- 数组属性
- 创建数组
- 从已有的数组创建数组
- 从数值范围创建数组
对象
import numpy as npa = np.array([1, 2, 3])print(a)b = np.array([[1, 2], [3, 4]])print(b)c = np.array([1, 2, 3, 4, 5], ndmin=2)print(c)d = np.array([1, 2, 3], dtype=complex)print(d)
数据类型
import numpy as npdt = np.dtype(np.int32)print(dt)dt = np.dtype('i4')print(dt)dt = np.dtype('>i4')print(dt)dt = np.dtype([('age', np.int8)])print(dt)dt = np.dtype([('age', np.int8)])a = np.array([(10,), (20,), (30,)], dtype=dt)print(a)dt = np.dtype([('age', np.int8)])a = np.array([(10,), (20,), (30,)], dtype=dt)print(a['age'])student = np.dtype([('name', 'S20'), ('age', 'i1'), ('marks', 'f4')])print(student)student = np.dtype([('name', 'S20'), ('age', 'i1'), ('marks', 'f4')])a = np.array([('abc', 21, 50), ('xyz', 18, 75)], dtype=student)print(a)
数组属性
import numpy as npa = np.arange(24)print(a.ndim) b = a.reshape(2, 4, 3) print(b.ndim)a = np.array([[1, 2, 3], [4, 5, 6]])print(a.shape)a = np.array([[1, 2, 3], [4, 5, 6]])a.shape = (3, 2)print(a)a = np.array([[1, 2, 3], [4, 5, 6]])b = a.reshape(3, 2)print(b)x = np.array([1, 2, 3, 4, 5], dtype=np.int8)print(x.itemsize)y = np.array([1, 2, 3, 4, 5], dtype=np.float64)print(y.itemsize)x = np.array([1, 2, 3, 4, 5])print(x.flags)
创建数组
import numpy as npx = np.empty([3, 2], dtype=int)print(x) x = np.zeros(5)print(x)y = np.zeros((5,), dtype=np.int_)print(y)z = np.zeros((2, 2), dtype=[('x', 'i4'), ('y', 'i4')])print(z)x = np.ones(5)print(x)x = np.ones([2, 2], dtype=int)print(x)
从已有的数组创建数组
import numpy as npx = [1, 2, 3]a = np.asarray(x)print(a)x = (1, 2, 3)a = np.asarray(x)print(a)x = [(1, 2, 3), (4, 5)]a = np.asarray(x)print(a)x = [1, 2, 3]a = np.asarray(x, dtype=float)print(a)s = b'Hello World'a = np.frombuffer(s, dtype='S1')print(a)list = range(5) it = iter(list)x = np.fromiter(it, dtype=float) print(x)
从数值范围创建数组
import numpy as npx = np.arange(5)print(x)x = np.arange(5, dtype=float)print(x)x = np.arange(10, 20, 2)print(x)a = np.linspace(1, 10, 10)print(a)a = np.linspace(1, 1, 10)print(a)a = np.linspace(10, 20, 5, endpoint=False)print(a)a = np.linspace(1, 10, 10, retstep=True)print(a)b = np.linspace(1, 10, 10).reshape([10, 1])print(b)a = np.logspace(1.0, 2.0, num=10)print(a)a = np.logspace(0, 9, 10, base=2)print(a)