修改Numpy数组以存储任意长度的字符串

修改Numpy数组以存储任意长度的字符串

NumPy建立在成功的Numeric数组对象的基础上(并且是其继承者)。它的目标是为科学计算创建一个有用的环境的基石。NumPy提供了两个基本对象:一个N维数组对象(ndarray)和一个通用函数对象(ufunc)。

任何包含字符串值的numpy数组的dtype是该数组中任何字符串的最大长度。一旦设定,它只能存储长度不超过创建时的最大长度的新字符串。如果我们试图重新分配另一个长度大于现有元素最大长度的字符串值,它会简单地丢弃所有超过最大长度的值。

在这篇文章中,我们将讨论如何克服这个问题并创建一个任意长度的numpy数组。

让我们首先直观地看到创建一个任意长度的字符串类型的numpy数组的问题。

# importing numpy as np
import numpy as np
  
# Create the numpy array
country = np.array(['USA', 'Japan', 'UK', '', 'India', 'China'])
  
# Print the array
print(country)

输出 :
修改Numpy数组以存储任意长度的字符串

正如我们在输出中看到的,在给定的数组中,任何字符串长度的元素的最大长度是5。 让我们尝试在数组中的缺失值的地方分配一个具有更大长度的值。

# Assign 'New Zealand' at the place of missing value
country[country == ''] = 'New Zealand'
  
# Print the modified array
print(country)

输出 :
修改Numpy数组以存储任意长度的字符串

正如我们在输出中看到的,由于长度的限制,”New Z “而不是 “New Zealand “被指定。现在,让我们看看有什么方法可以克服这个问题。

问题#1 :创建一个任意长度的numpy数组。

解决方案 :在创建数组时,将 “对象 “dtype分配给它。这让你拥有python字符串的所有行为。

# importing the numpy library as np
import numpy as np
  
# Create a numpy array
# set the dtype to object
country = np.array(['USA', 'Japan', 'UK', '', 'India', 'China'], dtype = 'object')
  
# Print the array
print(country)

输出 :

修改Numpy数组以存储任意长度的字符串

现在我们将在给定数组中的缺失值的位置上分配一个任意长度的值。

# Assign 'New Zealand' to the missing value
country[country == ''] = 'New Zealand'
  
# Print the array
print(country)

输出 :

修改Numpy数组以存储任意长度的字符串

正如我们在输出中看到的,我们已经成功地将一个任意长度的字符串分配给了给定的数组对象。

问题#2 :创建一个任意长度的numpy数组。

解决方案:我们将使用numpy.astype()函数来改变给定数组对象的dtype。

# importing the numpy library as np
import numpy as np
  
# Create a numpy array
# Notice we have not set the dtype of the object
# this will lead to the length problem 
country = np.array(['USA', 'Japan', 'UK', '', 'India', 'China'])
  
# Print the array
print(country)

输出 :

修改Numpy数组以存储任意长度的字符串

现在我们将使用numpy.astype()函数改变给定数组对象的dtype。然后我们将给它分配一个任意长度的字符串。

# Change the dtype of the country
# object to 'U256'
country = country.astype('U256')
  
# Assign 'New Zealand' to the missing value
country[country == ''] = 'New Zealand'
  
# Print the array
print(country)

输出 :

修改Numpy数组以存储任意长度的字符串

正如我们在输出中看到的,我们已经成功地将一个任意长度的字符串分配给了给定的数组对象。

注意 :在这种情况下,改变dtype后,我们可以分配的字符串的最大长度是256。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程