左对齐数组元素并在 Numpy 中设置用于填充的字符
要左对齐数组元素并设置用于填充的字符,请在 Python Numpy 中使用 **numpy.char.ljust()** 方法。“**width**”参数是结果字符串的长度。“fillchar”参数是要用于填充的字符。
该函数返回一个 str 或 unicode 类型的输出数组,具体取决于输入类型。numpy.char 模块为 numpy.str_ 或 numpy.bytes_ 类型的数组提供了一组矢量化字符串操作。
步骤
首先,导入所需的库 -
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.ljust() 方法。“width”参数是结果字符串的长度。“fillchar”参数是要用于填充的字符 -
print("
Result...
",np.char.ljust(arr, width = 15, fillchar = '$'))
示例
import numpy as np # Create a One-Dimensional array of string 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 left-justify elements of an array and set the characters to use for padding, use the numpy.char.ljust() method in Python Numpy # The "width" parameter is the length of the resulting strings # The "fillchar" parameter is the character to use for padding print("
Result...
",np.char.ljust(arr, width = 15, fillchar = '$'))
输出
Array... ['Tom' 'John' 'Kate' 'Amy' 'Brad'] Array datatype... <U4 Array Dimensions... 1 Our Array Shape... (5,) Number of elements in the Array... 5 Result... ['Tom$$$$$$$$$$$$' 'John$$$$$$$$$$$' 'Kate$$$$$$$$$$$' 'Amy$$$$$$$$$$$$' 'Brad$$$$$$$$$$$']
广告