Python NumPy Array Data Type

Question:

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?

Asked By: Vedant Bhosale

||

Answers:

You need to set how many chars you want to insert. ('name',np.str_, 4) this expect each word has only four chars. Or use ('name','U10') for considering ten chars, ('name','U18') for considering 18 chars without specifying.

import numpy as np  

d=np.dtype([('name',np.str_, 4),('salary',np.int64)])  

# we can define dtype like below without specifying the length of words
# BUT we should pay attention 'U10' only considers ten chars
# OR 'U18' for considering 18 chars
# d=np.dtype([('name','U10'),('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'
Answered By: I'mahdi
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.