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
广告
© . All rights reserved.