在NumPy陣列中,為每個元素返回一個副本,其中去掉了前導字元


要返回一個去掉了前導字元的陣列副本,請使用Python NumPy中的**numpy.char.lstrip()**方法。"chars"引數用於設定一個字串,指定要刪除的字元集。如果省略或為None,則chars引數預設為刪除空格。chars引數不是字首;而是刪除其所有值的組合。

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

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

步驟

首先,匯入所需的庫:

import numpy as np

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

arr = np.array(['zzzzTomzzzz', 'zzzJohn', 'zKate ', 'zAmyzz', 'zBradz'])

顯示我們的陣列:

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.lstrip()方法:

print("
Result...
",np.char.lstrip(arr, 'z'))

示例

import numpy as np

# Create a One-Dimensional array of string with some leading and trailing characters
arr = np.array(['zzzzTomzzzz', 'zzzJohn', 'zKate ', 'zAmyzz', 'zBradz'])

# 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 leading characters removed, use the numpy.char.lstrip() method in Python Numpy # The "chars" parameter is used to set a string specifying the set of characters to be removed. # If omitted or None, the chars argument defaults to removing whitespace. # The chars argument is not a prefix; rather, all combinations of its values are stripped. print("
Result...
",np.char.lstrip(arr, 'z'))

輸出

Array...
['zzzzTomzzzz' 'zzzJohn' 'zKate ' 'zAmyzz' 'zBradz']

Array datatype...
<U11

Array Dimensions...
1

Our Array Shape...
(5,)

Number of elements in the Array...
5

Result...
['Tomzzzz' 'John' 'Kate ' 'Amyzz' 'Bradz']

更新於:2022年2月17日

64次檢視

啟動您的職業生涯

完成課程獲得認證

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