NumPy 中两个字符串数组的元素级字符串连接
要返回两个字符串数组的元素级字符串连接,请在 Python NumPy 中使用 **numpy.char.add()** 方法。
numpy.char 模块为 numpy.str_ 或 numpy.bytes_ 类型的数组提供了一组矢量化字符串操作。
函数 add() 返回字符串_ 或 unicode_ 的输出数组,具体取决于输入类型的形状与 x1 和 x2 相同。x1 和 x1 是输入数组。
步骤
首先,导入所需的库 -
import numpy as np
创建两个一维字符串数组
arr1 = np.array(['Bella', 'Tom', 'John', 'Kate', 'Amy', 'Brad']) arr2 = np.array(['Cio', 'Hanks', 'Ceo', 'Hudson', 'Adams', 'Pitt'])
显示数组 -
print("Array 1...
", arr1)
print("
Array 2...
", arr2)获取数组的类型 -
print("
Our Array 1 type...
", arr1.dtype)
print("
Our Array 2 type...
", arr2.dtype)获取数组的维度 -
print("
Our Array 1 Dimensions...
",arr1.ndim)
print("
Our Array 2 Dimensions...
",arr2.ndim)获取数组的形状 -
print("
Our Array 1 Shape...
",arr1.shape)
print("
Our Array 2 Shape...
",arr2.shape)要返回两个字符串数组的元素级字符串连接,请使用 numpy.char.add() 方法。arr1 和 arr2 是两个输入字符串数组 -
print("
Result...
",np.char.add(arr1,arr2))
示例
import numpy as np
# Create two One-Dimensional arrays of string
arr1 = np.array(['Bella', 'Tom', 'John', 'Kate', 'Amy', 'Brad'])
arr2 = np.array(['Cio', 'Hanks', 'Ceo', 'Hudson', 'Adams', 'Pitt'])
# Display the arrays
print("Array 1...
", arr1)
print("
Array 2...
", arr2)
# Get the type of the arrays
print("
Our Array 1 type...
", arr1.dtype)
print("
Our Array 2 type...
", arr2.dtype)
# Get the dimensions of the Arrays
print("
Our Array 1 Dimensions...
",arr1.ndim)
print("
Our Array 2 Dimensions...
",arr2.ndim)
# Get the shape of the Arrays
print("
Our Array 1 Shape...
",arr1.shape)
print("
Our Array 2 Shape...
",arr2.shape)
# To return element-wise string concatenation for two arrays of string, use the numpy.char.add() method in Python Numpy
# The arr1 and arr2 are the two input string arrays
print("
Result...
",np.char.add(arr1,arr2))输出
Array 1... ['Bella' 'Tom' 'John' 'Kate' 'Amy' 'Brad'] Array 2... ['Cio' 'Hanks' 'Ceo' 'Hudson' 'Adams' 'Pitt'] Our Array 1 type... <U5 Our Array 2 type... <U6 Our Array 1 Dimensions... 1 Our Array 2 Dimensions... 1 Our Array 1 Shape... (6,) Our Array 2 Shape... (6,) Result... ['BellaCio' 'TomHanks' 'JohnCeo' 'KateHudson' 'AmyAdams' 'BradPitt']
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP