Python | Numpy string array dtype length

Problem # 1: An empty array is given, the underlying data of which is of a string type. Find the dtype.

Solution: We will use the numpy.dtype attribute to check the dtype of the given object.

# import numpy library as np

import numpy as np

 
# Create an empty array

arr = np.array ([ `Ela` , ` Ed` , `Brook` , ` Sia` , `Katherine` ])

  
# Print array

print (arr)

Output:

Now we will check the dtype of this array object, whose underlying data is of string type.

# Print dtype

print (arr.dtype)

Output:

As we can see in the output, the dtype of this array object is & # 39; & lt; U9 & # 39; where 9 — the length of the longest string in the given array object.

Let`s test this by checking the length of the longest string in the given object.

# Use the function numpy vectorization

length_checker = np.vectorize ( len )

  
# Find the length of each element

arr_len = length_checker (arr)

 
# Print the length of each element

print (arr_len)

 
# Print the maximum value

print (arr_len. max ())

Output:

Problem # 2: An array is given with an empty array, the underlying data of which is of a string type. Find the dtype.

Solution: We will use the numpy.dtype attribute to check the dtype of the given object.

# import numpy library as np

import numpy as np

 
# Create an empty array

arr = np.array ([ `New York` , ` Lisbon` , `Beijing` , ` Quebec` ])

 
# Print array

print (arr)

Output:

Now we check the dtype of this array object, whose underlying data is of string type.

# Print dtype

print (arr.dtype)

Output:

As we can see in the output, the dtype of this array object is & # 39; & lt; U8 & # 39; where 8 — the length of the longest string in the given array object.

Let`s test this by checking the length of the longest string in this object.

# Use the function numpy vectorization

length_checker = np.vectorize ( len )

  
# Find the length of each element

arr_len = length_checker (arr)

 
# Print the length of each element

print (arr_len)

 
# Print the maximum value

print (arr_len. max ())

Output: