Python库numpy之七
Python库numpy之七
- 结构化数组
- 结构化数组赋值
结构化数组
结构化数组赋值
-
使用Python元组赋值
为结构化数组赋值的最简单方法是使用 python 元组。每个值应该是一个长度等于数组中字段数量的元组。元组的元素从左到右赋值数组的连续字段。import numpy as npif __name__ == "__main__":T1 = np.dtype([('name', 'S8'), ('salary', 'f4')])l_workers = np.array([("Sam", 1000.92), ("james He", 2000.15)], dtype=T1)print(l_workers)l_new_workers = np.resize(l_workers, (3,))l_new_workers[2] = ("Ashley", 2000.89)print(l_new_workers)
C:\numpy>python numpy_11.py [(b'Sam', 1000.92) (b'james He', 2000.15)] [(b'Sam', 1000.92) (b'james He', 2000.15) (b'Ashley', 2000.89)]
-
使用标量赋值
赋值给结构化元素的标量将赋值给所有字段。
标量赋值给结构化数组import sys import numpy as npif __name__ == "__main__":if len(sys.argv) < 2:n = 2else:n = int(sys.argv[1])print(n)T1 = np.dtype([('name', 'S8'), ('salary', 'f4')])x = np.zeros(n, dtype=T1)print(x)x[:] = 3print(x)
C:\numpy>python numpy_13.py 5 5 [(b'', 0.) (b'', 0.) (b'', 0.) (b'', 0.) (b'', 0.)] [(b'3', 3.) (b'3', 3.) (b'3', 3.) (b'3', 3.) (b'3', 3.)]
非结构化数组赋值给结构化数组
import sys import numpy as npif __name__ == "__main__":if len(sys.argv) < 2:n = 2else:n = int(sys.argv[1])print(n)T1 = np.dtype([('name', 'S8'), ('salary', 'f4')])x = np.zeros(n, dtype=T1)print(x)r1 = np.arange(n)print(r1)x[:] = r1print(x)
C:\numpy>python numpy_12.py 5 5 [(b'', 0.) (b'', 0.) (b'', 0.) (b'', 0.) (b'', 0.)] [0 1 2 3 4] [(b'0', 0.) (b'1', 1.) (b'2', 2.) (b'3', 3.) (b'4', 4.)]
结构化数组也可以赋值给非结构化数组,只要结构化数据类型只有一个字段
import sys import numpy as npif __name__ == "__main__":T1 = np.dtype([('name', 'S8')])x = np.zeros(3, dtype=T1)x[0] = ("John")x[1] = ("Sam")x[2] = ("Johnson")print("x type: {0}, val: {1}".format(type(x), x))non_struct = np.zeros(3, dtype='S8')print("non_struct type: {0}, val: {1}".format(type(non_struct), non_struct))non_struct = xprint("non_struct type: {0}, val: {1}".format(type(non_struct), non_struct))
C:\numpy>python numpy_14.py x type: <class 'numpy.ndarray'>, val: [(b'John',) (b'Sam',) (b'Johnson',)] non_struct type: <class 'numpy.ndarray'>, val: [b'' b'' b''] non_struct type: <class 'numpy.ndarray'>, val: [(b'John',) (b'Sam',) (b'Johnson',)]
-
使用另一个结构化数组赋值
两个结构化数组之间的赋值,就好像将源元素转换为元组,然后赋值给目标元素一样。也就是说,源数组的第一个字段将赋值给目标数组的第一个字段,第二个字段赋值给目标数组的第二个字段,依此类推。两个结构化数组的字段名称不同,不影响赋值。具有不同字段数的结构化数组不能互相赋值。未包含在任何字段中的目标结构的字节不受影响。import sys import numpy as npif __name__ == "__main__":T1 = [('a', 'i8'), ('b', 'f4'), ('c', 'S3')]T2 = [('x', 'f4'), ('y', 'S3'), ('z', 'O')]a = np.zeros(2, dtype=T1)a[0] = (1, 1.5, "abc")a[1] = (3, 5.76, "xyz")b = np.ones(2, dtype=T2)b[0] = (10, 51.15, "a1c")b[1] = (15, 15.76, "x1z")print(a)print(b)a[:] = bprint("a: {0}".format(a))print("b: {0}".format(b))
C:\numpy>python numpy_15.py [(1, 1.5 , b'abc') (3, 5.76, b'xyz')] [(10., b'51.', 'a1c') (15., b'15.', 'x1z')] a: [(10, 51., b'a1c') (15, 15., b'x1z')] b: [(10., b'51.', 'a1c') (15., b'15.', 'x1z')]