📌  相关文章
📜  Python| Numpy字符串数组的dtype对象长度

📅  最后修改于: 2022-05-13 01:54:33.607000             🧑  作者: Mango

Python| Numpy字符串数组的dtype对象长度

在这篇文章中,我们将看到当底层数据是字符串类型时 numpy 对象的数据类型。在 numpy 中,如果给定对象的基础数据类型是字符串,那么对象的 dtype 是数组中最长字符串的长度。之所以如此,是因为我们无法在 numpy 中创建可变长度字符串,因为 numpy 需要知道应该为字符串分配多少空间。

问题 #1:给定一个基础数据为字符串类型的 numpy 数组。找到数据类型。

解决方案:我们将使用numpy.dtype属性来检查给定对象的 dtype。

# 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)

输出 :

正如我们在输出中看到的,给定数组对象的 dtype 是' ,其中 9 是给定数组对象中最长字符串的长度。

让我们通过检查给定对象中最长字符串的长度来验证这一点。

# 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 数组。找到数据类型。

解决方案:我们将使用numpy.dtype属性来检查给定对象的 dtype。

# 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)

输出 :

现在我们将检查其底层数据为字符串类型的给定数组对象的 dtype。

# Print the dtype
print(arr.dtype)

输出 :

正如我们在输出中看到的,给定数组对象的 dtype 是' ,其中 8 是给定数组对象中最长字符串的长度。

让我们通过检查给定对象中最长字符串的长度来验证这一点。

# 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())

输出 :