1. 程式人生 > 其它 >numpy-array初始化時指定的dtype=[(‘x‘,‘i4‘),(‘y‘,‘i4‘)]引數

numpy-array初始化時指定的dtype=[(‘x‘,‘i4‘),(‘y‘,‘i4‘)]引數

技術標籤:numpy學習numpypython

今天看numpy文件時,遇到一個問題https://numpy.org/doc/stable/reference/generated/numpy.argsort.html#numpy.argsort,在初始化array時的引數dtype=[('x','i4'),('y','i4')],做個記錄:

x = np.array([(1, 1000), (0, 1111)], dtype=[('x', '<i4'), ('y', '<i4')])

這裡的dtype的作用:給array中初始化值指定名字和資料型別。每一項初始化值的第一項被指定為'x',第二項被指定為'y'。

分別使用名字索引訪問x中的元素:

print(x['x'])  # 輸出 [1 0]
print(x['y'])  # 輸出 [1000 1111]

還可以通過'x'修改x中的值

x['x'] = np.array([2000, 2222])
print(x)  # 輸出 [(2000, 1000) (2222, 1111)]

'<i4'表示具體的資料型別'little-endian 32-bit signed integer',具體見https://numpy.org/doc/stable/reference/arrays.dtypes.html#arrays-dtypes-constructing

參考:

https://stackoverflow.com/questions/51364975/datatype-in-numpy