NumPy char.add() 函式



NumPy 的char.add()函式用於執行元素級的字串連線。當我們提供兩個字串陣列時,此函式透過返回一個新的連線字串陣列來組合每個陣列中對應的元素。

如果輸入陣列的形狀不同,則 NumPy 會根據廣播規則將其廣播到相容的形狀。此函式對於有效地操作和組合 NumPy 陣列中的字串資料非常有用。

語法

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

numpy.char.add(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])

引數

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

  • x1, x2 (array_like) - 這些是要相加的輸入陣列。

  • out (可選) - 這是存放結果的輸出陣列。

  • where (array_like, 可選) - 這是一個布林陣列,指定應用條件的位置。

  • **kwargs - 引數如 casting、order、dtype、subok 是附加的關鍵字引數,可根據需要使用。

返回值

此函式返回包含 x1 和 x2 之和結果的陣列。

示例 1

以下是 NumPy char.add() 函式的基本示例。在此示例中,我們對字串進行元素級連線:

import numpy as np

# Define two arrays of strings
a = np.array(['Hello', 'Learners', ','])
b = np.array([' Welcome', ' Tutorialspoint !', 'to'])

# Concatenate the strings element-wise
result = np.char.add(a, b)

print(result)

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

['Hello Welcome' 'Learners Tutorialspoint !' ',to']

示例 2

當與廣播一起使用char.add() 函式時,只要它們可以廣播到公共形狀,我們就可以連線不同形狀的陣列。以下是一個示例:

import numpy as np

# Define a 1D array of strings
a = np.array(['Hello', 'Goodbye'])

# Define a 2D array of strings
b = np.array(['!', '!!!'])

# Broadcasting the 1D array with the 2D array and concatenating
result = np.char.add(a[:, np.newaxis], b)

print(result)

以下是上述示例的輸出:

[['Hello!' 'Hello!!!']
 ['Goodbye!' 'Goodbye!!!']]

示例 3

這是一個另一個示例,它演示了使用char.add() 函式對字串進行元素級連線的字串連線:

import numpy as np 

# Basic concatenation
print('Concatenate two strings:')
print(np.char.add(['hello'], [' xyz']))
print('\n')

# Example with multiple strings
print('Concatenation example:')
print(np.char.add(['hello', 'hi'], [' abc', ' xyz']))

以下是上述示例的輸出:

Concatenate two strings:
['hello xyz']


Concatenation example:
['hello abc' 'hi xyz']
numpy_string_functions.htm
廣告