NumPy 中元素級字串多次連線的返回值


要返回元素級字串多次連線,請在 Python NumPy 中使用 **numpy.char.multiply()** 方法。multiply() 函式根據輸入型別返回字串或 unicode_ 的輸出陣列。

numpy.char 模組為型別為 numpy.str_ 或 numpy.bytes_ 的陣列提供了一組向量化字串操作。

步驟

首先,匯入所需的庫 -

import numpy as np

建立一個字串的一維陣列 -

arr = np.array(['Bella', 'Tom', 'John', 'Kate', 'Amy', 'Brad'])

顯示我們的陣列 -

print("Array...
",arr)

獲取資料型別 -

print("
Array datatype...
",arr.dtype)

獲取陣列的維度 -

print("
Array Dimensions...
",arr.ndim)

獲取陣列的形狀 -

print("
Our Array Shape...
",arr.shape)

獲取陣列的元素個數 -

print("
Elements in the Array...
",arr.size)

i 的值是要重複字串的次數 -

i = 4

要返回元素級字串多次連線,請使用 numpy.char.multiply() 方法。arr1 和 arr2 是我們兩個輸入字串陣列 -

print("
Result...
",np.char.multiply(arr,i))

示例

import numpy as np

# Create a One-Dimensional array of string
arr = np.array(['Bella', 'Tom', 'John', 'Kate', 'Amy', 'Brad'])

# Displaying our array
print("Array...
",arr) # Get the datatype print("
Array datatype...
",arr.dtype) # Get the dimensions of the Array print("
Array Dimensions...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # Get the number of elements of the Array print("
Elements in the Array...
",arr.size) # The value of i is the number of times to repeat the string i = 4 # To return element-wise string multiple concatenation, use the numpy.char.multiply() method in Python Numpy # The arr1 and arr2 are out two input string arrays print("
Result...
",np.char.multiply(arr,i))

輸出

$python3 main.py
Array...
['Bella' 'Tom' 'John' 'Kate' 'Amy' 'Brad']

Array datatype...
<U5

Array Dimensions...
1

Our Array Shape...
(6,)

Elements in the Array...
6

Result...
['BellaBellaBellaBella' 'TomTomTomTom' 'JohnJohnJohnJohn'
'KateKateKateKate' 'AmyAmyAmyAmy' 'BradBradBradBrad']

更新於: 2022年2月17日

161 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告