在 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.