在 NumPy 中返回字符串的副本,其中所有出现的子字符串 old 都被 new 替换。


要返回字符串的副本,其中所有出现的子字符串 old 都被 new 替换,请在 Python NumPy 中使用 **numpy.char.replace()** 方法 -

  • 第一个参数是输入数组
  • 第二个参数是要替换的旧字符串
  • 第三个参数是要替换旧字符串的新字符串

如果给出了可选参数 count,则只替换前 count 个出现。

numpy.char 模块为类型为 numpy.str_ 或 numpy.bytes_ 的数组提供了一组矢量化的字符串操作。

步骤

首先,导入所需的库 -

import numpy as np

创建一个数组 -

arr = np.array(["Welcome to the Jungle", "Jungle Safari"])

显示我们的数组 -

print("Array...
",arr)

获取数据类型 -

print("
Array datatype...
",arr.dtype)

获取数组的维度 -

print("
Array Dimensions...
",arr.ndim)

获取数组的形状 -

print("
Our Array Shape...
",arr.shape)

获取数组的元素数量 -

print("
Elements in the Array...
",arr.size)

要返回字符串的副本,其中所有出现的子字符串 old 都被 new 替换,请在 Python NumPy 中使用 numpy.char.replace() 方法 -

print("
Result...
",np.char.replace(arr, 'Jungle', 'Club'))

示例

import numpy as np

# Create an array
arr = np.array(["Welcome to the Jungle", "Jungle Safari"])

# Displaying our Array
print("Array...
",arr) # Get the datatype print("
Array datatype...
",arr.dtype) # Get the dimensions of the Array print("
Array Dimensions...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # Get the number of elements of the Array print("
Elements in the Array...
",arr.size) # To return a copy of the string with all occurrences of substring old replaced by new, use the numpy.char.replace() method in Python Numpy # The 1st parameter is the input array # The 2nd parameter is the old string to be replaced # The 3rd parameter is the new string to be replaced with the old print("
Result...
",np.char.replace(arr, 'Jungle', 'Club'))

输出

Array...
['Welcome to the Jungle' 'Jungle Safari']

Array datatype...
<U21

Array Dimensions...
1

Our Array Shape...
(2,)

Elements in the Array...
2

Result...
['Welcome to the Club' 'Club Safari']

更新于: 2022年2月18日

116 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.