在 NumPy 中,如何逐元素返回字串的副本,並將大寫字元轉換為小寫,反之亦然


要逐元素返回字串的副本,並將大寫字元轉換為小寫,反之亦然,可以使用 Python NumPy 中的 **numpy.char.swapcase()** 方法。對於 8 位字串,此方法依賴於區域設定。

函式 swapcase() 返回一個 str 或 unicode 型別的輸出陣列,具體取決於輸入型別。numpy.char 模組為 numpy.str_ 或 numpy.bytes_ 型別的陣列提供了一組向量化的字串操作。

步驟

首先,匯入所需的庫:

import numpy as np

建立一個一維字串陣列:

arr = np.array(['Katie', 'JOHN', 'Kate', 'AmY', 'brADley'])

顯示我們的陣列:

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

print("
Result (swapcases)...
",np.char.swapcase(arr))

示例

import numpy as np

# Create a One-Dimensional array of strings
arr = np.array(['Katie', 'JOHN', 'Kate', 'AmY', 'brADley'])

# 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 element-wise a copy of the string with uppercase characters converted to lowercase and vice versa, use the numpy.char.swapcase() method in Python Numpy print("
Result (swapcases)...
",np.char.swapcase(arr))

輸出

Array...
['Katie' 'JOHN' 'Kate' 'AmY' 'brADley']

Array datatype...
<U7

Array Dimensions...
1

Our Array Shape...
(5,)

Number of elements in the Array...
5

Result (swapcases)...
['kATIE' 'john' 'kATE' 'aMy' 'BRadLEY']

更新於: 2022年2月22日

246 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.