對於 NumPy 陣列中的每個元素,返回一個已去除尾部空格的副本。


要返回一個已去除尾部空格的陣列副本,請在 Python NumPy 中使用 **numpy.char.rstrip()** 方法。

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

chars 引數是一個字串,指定要刪除的字元集。如果省略或為 None,則 chars 引數預設為刪除空格。chars 引數不是字尾;相反,它會去除其所有值的組合。

步驟

首先,匯入所需的庫:

import numpy as np

建立一個包含一些前導和尾隨空格的字串的一維陣列:

arr = np.array([' 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)

要返回一個已去除尾部空格的陣列副本,請使用 numpy.char.rstrip() 方法:

print("
Result...
",np.char.rstrip(arr))

示例

import numpy as np

# Create a One-Dimensional array of string with some leading and trailing spaces
arr = np.array([' 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("
Number of elements in the Array...
",arr.size) # To return a copy of an array with the trailing spaces removed, use the numpy.char.rstrip() method in Python Numpy print("
Result...
",np.char.rstrip(arr))

輸出

Array...
[' Tom ' ' John ' ' Kate ' ' Amy ' 'Brad ']

Array datatype...
<U6

Array Dimensions...
1

Our Array Shape...
(5,)

Number of elements in the Array...
5

Result...
[' Tom' ' John' ' Kate' ' Amy' 'Brad']

更新於:2022年2月18日

83 次瀏覽

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.