NumPy char.replace() 函式



NumPy 的char.replace() 函式允許替換陣列中每個字串元素中指定的子字串為新的子字串。它按元素進行操作,這意味著替換髮生在陣列中的每個字串中。

我們可以透過指定 count 引數來選擇性地限制替換次數。此函式對於透過確保整個資料集中的一致替換來有效地修改字串陣列中的文字資料很有用。

語法

以下是 NumPy char.replace() 函式的語法:

char.replace(a, old, new, count=-1)

引數

以下是 NumPy char.replace() 函式的引數:

  • a(類似陣列的 str 或 unicode):包含將發生替換的字串的輸入陣列。

  • old(str):我們要替換的子字串。

  • new(str):包含將發生替換的字串的輸入陣列。

  • old(str):將替換舊子字串的子字串。

  • count(int,可選):每個字串中要替換的最大出現次數。如果未指定,則替換所有出現次數。

返回值

此函式返回一個與輸入形狀相同的陣列,其中原始字串被替換為新定義的字串。

示例 1

以下是 NumPy char.replace() 函式的基本示例,其中我們有一個水果名稱陣列,我們正在替換每個水果名稱字串中的字母“a”為字母“o”:

import numpy as np

arr = np.array(['apple', 'banana', 'cherry'])
result = np.char.replace(arr, 'a', 'o')
print(result)

以下是numpy.char.replace() 函式基本示例的輸出:

['opple' 'bonono' 'cherry']

示例 2

char.replace() 函式允許我們用定義的子字串替換整個字串。在此示例中,陣列中每個元素中的字串“world”都被替換為“universe”:

import numpy as np
arr = np.array(['hello world', 'world of numpy', 'worldwide'])
print("Original Array:", arr)
result = np.char.replace(arr, 'world', 'universe')
print("Replaced Array:",result)

以下是將字串替換為定義字串的輸出:

Original Array: ['hello world' 'world of numpy' 'worldwide']
Replaced Array: ['hello universe' 'universe of numpy' 'universewide']

示例 3

如果我們只想替換一定數量的出現次數,則可以在char.replace() 函式中指定 count 引數。以下是將每個字串中第一次出現的“is”替換為“was”的示例:

import numpy as np
arr = np.array(['this is a test', 'this is another test'])
print("Original String:", arr)
result = np.char.replace(arr, 'is', 'was', count=1)
print("Replaced string:",result) 

以下是限制替換次數的輸出:

Original String: ['this is a test' 'this is another test']
Replaced string: ['thwas is a test' 'thwas is another test']
numpy_string_functions.htm
廣告