Python | Длина объекта dtype массива строк Numpy

Опубликовано: 12 Апреля, 2022

В этом посте мы увидим тип данных объекта numpy, когда базовые данные имеют строковый тип. В numpy, если базовым типом данных данного объекта является строка, то dtype объекта - это длина самой длинной строки в массиве. Это потому, что мы не можем создать строку переменной длины в numpy, поскольку numpy нужно знать, сколько места должно быть выделено для строки.

Проблема №1: Для массива numpy, базовые данные которого имеют строковый тип. Найдите dtype.

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

# importing the numpy library as np
import numpy as np
  
# Create a numpy array
arr = np.array(["Ela", "Ed", "Brook", "Sia", "Katherine"])
  
# Print the array
print(arr)

Выход :

Теперь мы проверим dtype данного объекта массива, базовые данные которого относятся к строковому типу.

# Print the dtype
print(arr.dtype)

Output :

As we can see in the output, the dtype of the given array object is "<U9" where 9 is the length of the longest string in the given array object.

Let’s verify this by checking the length of the longest string in the given object.

# Use vectorize function of numpy
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())

Выход :



Проблема № 2: Для массива numpy, базовые данные которого имеют строковый тип. Найдите dtype.

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

# importing the numpy library as np
import numpy as np
  
# Create a numpy array
arr = np.array(["New York", "Lisbon", "Beijing", "Quebec"])
  
# Print the array
print(arr)

Выход :

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

# Print the dtype
print(arr.dtype)

Output :

As we can see in the output, the dtype of the given array object is "<U8" where 8 is the length of the longest string in the given array object.

Let’s verify this by checking the length of the longest string in the given object.

# Use vectorize function of numpy
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())

Выход :

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.