返回 NumPy 数组元素的截断值


要返回数组元素的截断值,请在 Python NumPy 中使用 **numpy.trunc()** 方法。该函数返回 x 中每个元素的截断值。如果 x 是标量,则此函数返回标量。标量 x 的截断值是比 x 更靠近零的整数 i。简而言之,带符号数 x 的小数部分被丢弃。

out 是存储结果的位置。如果提供,它必须具有输入广播到的形状。如果未提供或为 None,则返回一个新分配的数组。元组(仅可能作为关键字参数)的长度必须等于输出的数量。

条件在输入上广播。在条件为 True 的位置,out 数组将设置为 ufunc 结果。在其他地方,out 数组将保留其原始值。请注意,如果通过默认的 out=None 创建了一个未初始化的 out 数组,则其中条件为 False 的位置将保持未初始化。

步骤

首先,导入所需的库 -

import numpy as np

使用 array() 方法创建一个数组 -

arr = np.array([31.7, 27.4, -100.8, 50, -10.5, 76.8, -87.6])

显示数组 -

print("Array...", arr)

获取数组的类型 -

print("Our Array type...", arr.dtype)

获取数组的维度 -

print("Our Array Dimensions...", arr.ndim)

获取数组中元素的数量 -

print("Number of elements...", arr.size)

要返回数组元素的截断值,请在 Python NumPy 中使用 numpy.trunc() 方法 -

print("Result (truncate)...",np.trunc(arr))

示例

Open Compiler
import numpy as np # Create an array using the array() method arr = np.array([31.7, 27.4, -100.8, 50, -10.5, 76.8, -87.6]) # Display the array print("Array...", arr) # Get the type of the array print("Our Array type...", arr.dtype) # Get the dimensions of the Array print("Our Array Dimensions...", arr.ndim) # Get the number of elements in the Array print("Number of elements...", arr.size) # To return the truncated value of the array elements, use the numpy.trunc() method in Python Numpy print("Result (truncate)...",np.trunc(arr))

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

Array...
[ 31.7 27.4 -100.8 50. -10.5 76.8 -87.6]

Our Array type...
float64

Our Array Dimensions...
1

Number of elements...
7

Result (truncate)...
[ 31. 27. -100. 50. -10. 76. -87.]

更新于: 2022年2月16日

1K+ 次查看

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告