使用标量赋值
赋值给结构化元素的标量将赋值给所有字段。
标量赋值给结构化数组
import sys
import numpy as np
if __name__ == "__main__":
if len(sys.argv) < 2:
n = 2
else:
n = int(sys.argv[1])
print(n)
T1 = np.dtype([('name', 'S8'), ('salary', 'f4')])
x = np.zeros(n, dtype=T1)
print(x)
x[:] = 3
print(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 np
if __name__ == "__main__":
if len(sys.argv) < 2:
n = 2
else:
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[:] = r1
print(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 np
if __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 = x
print("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',)]