简体   繁体   中英

Python NumPy Array Data Type

import numpy as np  

d=np.dtype([('name',np.str_),('salary',np.int64)])  
arr = np.array([('Vedant',80000),('Subodh',4000)],dtype=d)  
print(arr)  

Output:

[('', 80000) ('',  4000)]

Why are the strings blank?

You need to set how many chars you want to insert. ('name',np.str_, 4) this expect each word has only four chars.

import numpy as np  

d=np.dtype([('name',np.str_, 4),('salary',np.int64)])  
arr = np.array([('abcde',80000),('Subodh',4000)],dtype=d)  
print(arr)  
# [('abcd', 80000) ('Subo',  4000)]
# skip 'e' from 'abcde'
# skip 'dh' from 'Subodh'

You can define shape too.

# we expect each array has shape=(2,2)
d = np.dtype([('name',np.str_, 4),('salary',np.int64, (2,2))])  
arr = np.array([('abcde',80000),('Subodh',[[10,20],[30,40]])],dtype=d)  
print(arr)   
# [('abcd', [[80000, 80000], [80000, 80000]]) # Because 80000 does not have shape=(2,2) item repeat to create array with shape=(2,2)
#  ('Subo', [[   10,    20], [   30,    40]])]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM