返回 NumPy 序列中字串的連線字串


要返回一個字串,該字串是序列中字串的連線,請在 Python NumPy 中使用 **numpy.char.join()** 方法。第一個引數是分隔符陣列。第二個引數是序列陣列。該函式返回一個 str 或 unicode 的輸出陣列,具體取決於輸入型別。

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

步驟

首先,匯入所需的庫 -

import numpy as np

建立字串的一維陣列 -

arr = np.array(['Bella\tCio', 'Tom\tHanks', 'Monry\tHeist\tSeries'])

顯示我們的陣列 -

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)

要將字串陣列中的製表符替換為固定的製表符大小,請使用 numpy.char.expandtabs() 方法。“tabsize”引數用於將製表符替換為 tabsize 個空格。如果未給出,則預設為 8 個空格。我們已將“tabsize”設定為 10,即 10 個空格 -

print("
Result (expand tabs)...
",np.char.expandtabs(arr, tabsize = 10))

示例

import numpy as np

# Create two arrays
sep = np.array([':', '-', '$'])
seq = np.array(['abc', 'def', 'ghi'])

# Displaying our sequence
print("Sequence array...
",seq) # Get the datatype print("
Array datatype...
",seq.dtype) # Get the dimensions of the Array print("
Array Dimensions...
",seq.ndim) # Get the shape of the Array print("
Our Array Shape...
",seq.shape) # Get the number of elements of the Array print("
Elements in the Array...
",seq.size) # To return a string which is the concatenation of the strings in the sequence, use the numpy.char.join() method in Python Numpy # The 1st parameter is the separator array # The 2nd parameter is the sequence array print("
Result...
",np.char.join(sep,seq))

輸出

Sequence array...
['abc' 'def' 'ghi']

Array datatype...
<U3

Array Dimensions...
1

Our Array Shape...
(3,)

Elements in the Array...
3

Result...
['a:b:c' 'd-e-f' 'g$h$i']

更新於: 2022年2月17日

67 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告