3

I have an awkward array of type float and I need it to be of type int. Something equivalent to the following numpy snippet:

import numpy as np
import awkward as ak

arr = np.array([1., 2., 3.])
arr = arr.astype(int)

arr2 = ak.Array(np.array([1., 2., 3.]))
arr2 = arr2.???
Jim Pivarski
  • 5,568
  • 2
  • 35
  • 47
HEP N008
  • 187
  • 8

2 Answers2

2

If you have an awkward array, arr, where:

>>> arr.type
20 * float64

You can simply use ak.values_astype:

>>> arr = ak.values_astype(arr, "int64")
>>> arr
20 * int64
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
HEP N008
  • 187
  • 8
-1

this is how you could change all values within an array from float to int:

# Example array
arr_float = [3.45, 5.6, 3.89, 10.1]

# to integer values 
arr_int = [int(n) for n in arr_float] # this is a list comprehension
arr_int
>>> [3, 5, 3, 10] # float values to integer get always rounded down to whole number

Alternatively, you make the the array an numpy array and proceed like in your question:

import numpy as np

# Example array
arr_float = [3.45, 5.6, 3.89, 10.1]

# to numpy array
arr_np = np.array(arr_float)

arr_np.astype(int)
>>> array([ 3,  5,  3, 10])

This would be a function that is callable whenever you need to change:

# Function changing float values to integer values
def to_int(input_array):
    return [int(n) for n in input_array]

# Example array
arr_float = [3.86, 2.9999, 9.46, 3.00013, 8.56]

to_int(arr_float)
>>> [3, 2, 9, 3, 8]
Maexel
  • 94
  • 5
  • 2
    The question was asking about the Awkward Array library; I've edited it to make that clearer. – Jim Pivarski Jan 07 '21 at 21:12
  • My bad. Wasn't paying enough attention. – Maexel Jan 07 '21 at 23:11
  • The other issue with this code, from my usage standpoint, is that it would take way too long. Looping in Python is very slow, while proper broadcasting is pretty quick; though what you posted would certainly work for shorter arrays. – HEP N008 Jan 20 '21 at 00:49