Numpy Floor Float Valeurs à Int

Nov 23 2020

J'ai un tableau de flottants et je veux les soler à l'entier le plus proche, afin que je puisse les utiliser comme indices.

Par exemple:

In [2]: import numpy as np

In [3]: arr = np.random.rand(1, 10) * 10

In [4]: arr
Out[4]:
array([[4.97896461, 0.21473121, 0.13323678, 3.40534157, 5.08995577,
        6.7924586 , 1.82584208, 6.73890807, 2.45590354, 9.85600841]])

In [5]: arr = np.floor(arr)

In [6]: arr
Out[6]: array([[4., 0., 0., 3., 5., 6., 1., 6., 2., 9.]])

In [7]: arr.dtype
Out[7]: dtype('float64')

Ils flottent toujours après le revêtement de sol, existe-t-il un moyen de les convertir automatiquement en nombres entiers?

Réponses

2 Jocker Nov 23 2020 at 12:01

Je suis modifier la réponse avec l'explication @DanielF: "le plancher ne se convertit pas en entier, il donne juste des flottants à valeur entière, donc vous avez toujours besoin d'un astype pour changer en int" Vérifiez ce code pour comprendre la solution:

import numpy as np
arr = np.random.rand(1, 10) * 10
print(arr)
arr = np.floor(arr).astype(int)
print(arr)
OUTPUT:
[[2.76753828 8.84095843 2.5537759  5.65017407 7.77493733 6.47403036
  7.72582766 5.03525625 9.75819442 9.10578944]]
[[2 8 2 5 7 6 7 5 9 9]]
1 vegiv Nov 23 2020 at 12:08

Pourquoi ne pas simplement utiliser:

np.random.randint(1,10)