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']

更新於: 2022年2月17日

347 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.