Why do I have to use np.string_? Why can't I use np.string without the underscore?

Viewed 395

I just started learning NumPy, so I'm still a bit dazed with all of its ins and outs. I'm learning how to create arrays with specific data types. I'm a bit confused with this:

When I create an array of int32 data type, it shows just that:

a = np.zeros((2, 3), dtype=np.int32)
print(a)
print(a.dtype)

The print statement shows: int32

When I create an array of float data type, it shows just that:

a = np.array([1, 2, 3, 4], dtype=np.float)
print(a)
print(a.dtype)

The print statement shows: float64

However, when I create an array of data type string, it doesn't have a similar output:

a = np.array([1,2,3,4,5,6], dtype=np.string_)

print(a)
print(a.dtype)

The print statement shows:

[b'1' b'2' b'3' b'4' b'5' b'6']
|S1

Why? What does it mean? Also, why can't I choose dtype=np.string? Why do I need the underscore dtype=np.string_?

2 Answers

As you can see, if you simply do:

>>> np.string_
<class 'numpy.bytes_'>
>>> 

It automatically gives a numpy.bytes_ object for each value.'

So you should do np.str_ as follows:

>>> np.array([1,2,3,4,5,6], dtype=np.str_)
array(['1', '2', '3', '4', '5', '6'], dtype='<U1')
>>> 

Which gives a regular numpy scalar string dtype, which is the same as regular str.

Using just str would be easier:

>>> np.array([1,2,3,4,5,6], dtype=str)
array(['1', '2', '3', '4', '5', '6'], dtype='<U1')
>>> 

What does it mean?

Simply speaking S1 is length-1 string, consider following example

import numpy as np
arr1 = np.array(['A','A','A'],dtype=np.string_)
arr3 = np.array(['ABC','ABC','ABC'],dtype=np.string_)
arr5 = np.array(['ABCDE','ABCDE','ABCDE'],dtype=np.string_)
print(arr1.dtype)  # |S1
print(arr3.dtype)  # |S3
print(arr5.dtype)  # |S5

Note analogy with another numpy datatypes - if you know you have certain number of say length-5 strings, you can easily compute memory required as in case of say uint8 or int32 and as opposed to variable length strings.

Related