怎么对2维的numpy array取整?

  统计/机器学习 Python    浏览次数:17913        分享
3

我有一个2维的numpy array,里面数值有小数,我想对整个array取整

s = np.int(s)

用np.int之后直接就报错了

TypeError: only length-1 arrays can be converted to Python scalars

看来np.int只对1维array有效,那么2维的应该怎么取整?



 

panling   2017-10-31 11:11



   2个回答 
9

取整的方法有很多,比如另外一个答案里的astype(int)。此外还有截取np.trunc,向上取整np.ceil,向下取整np.floor,四舍五入取整np.rint。

>>> x
array([[ 1. ,  2.3],
       [ 1.3,  2.9]])
>>> a = np.trunc(x)
>>> a
array([[ 1.,  2.],
       [ 1.,  2.]])
>>> b = np.ceil(x)
>>> b
array([[ 1.,  3.],
       [ 2.,  3.]])
>>> c = np.floor(x)
>>> c
array([[ 1.,  2.],
       [ 1.,  2.]])
>>> d = np.rint(x)
>>> d
array([[ 1.,  2.],
       [ 1.,  3.]])


SofaSofa数据科学社区DS面试题库 DS面经

sasa   2017-11-01 14:22

3


s = s.astype(np.int)


SofaSofa数据科学社区DS面试题库 DS面经

派大星   2017-10-31 13:59



  相关讨论

numpy里tile函数是怎么用的?

numpy里的np.clip函数怎么用?

numpy array中元素的个数?

'numpy.ndarray' object has no attribute 'head'

如何查看当前numpy版本,升级numpy?

numpy里的无穷大np.inf到底是多大呢?

求一个nxn的numpy array的对角线的和?

如何在numpy array尾部增加一行

调用np.average()时报错TypeError: No loop matching

numpy array里怎么用fillna填充nan的值?

  随便看看

python产生服从常用概率分布的随机数

python怎么对list中的元素做连乘?

python里清除已经定义过的变量

为什么过拟合不好?

把tf.Tensor转换为numpy array