在 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']
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP