Convert an array into Int

Hi,

If I have an 2D array of multiple elements (named aux), how do I convert or ensure that they are integers? Also note that I didn’t create this array, it was copied from a dataframe, which was in turn taken from a CSV file. I don’t know if that is relevant but thought it might be better to mention. I tried round(Int, aux) but it doesn’t work. I get the following error:

ERROR: MethodError: objects of type Array{ConstraintRef{Model,C,Shape} where Shape<:AbstractShape where C,1} are not callable
Use square brackets [] for indexing an Array.

Here’s an MWE

df2 = DataFrame(csv2)
aux = df2.T

Thanks!

Try using the convert function

convert(T, x)

Convert x to a value of type T.

If T is an Integer type, an InexactError will be raised if x is not representable by T, for example if x is not
integer-valued, or is outside the range supported by T.

Examples
≡≡≡≡≡≡≡≡≡≡

julia> convert(Int, 3.0)
3

julia> convert(Int, 3.5)
ERROR: InexactError: Int64(3.5)
Stacktrace:
[…]

If T is a AbstractFloat or Rational type, then it will return the closest value to x representable by T.

1 Like

Thanks for the suggestion, but it doesn’t accept arrays apparerntly. So I tried using a for loop

for i = 1:100 
     convert(Int, aux[i])
end

I think it momentarily converts to integer but then it goes back to float. The entire array is actually integer except for one value, because I wanted to experiment. But because of that one float value, the entire array becomes float.

julia> aux[1]
1.0

julia> convert(Int, aux[1])
1

julia> aux[1]
1.0

This documentation might help
https://docs.julialang.org/en/v1/manual/conversion-and-promotion/

The element type of an array is fixed and cannot be changed. You can create a new array with the result of converting all elements to Int with e.g. Int.(aux).

8 Likes

Thank you!

This works great. So, why doesn’t it work when I put it in a loop?

I have a Dict ‘m’ with several arrays of floats I want to convert to ints.

No problem going though the individual Arrays in this dict one by one:

m[“Array1”] = Int.(m[“Array1”])
m[“Array1”] = Int.(m[“Array1”])

This works perfectly, but when I try to make a loop to process the multiple arrays in less lines, like:

for i in [m[“Array1”], m[“Array2”], m[“Array3”]]
i = Int.(i)
end

They don’t convert… :frowning:

How can I get Int.(…) working in a loop like this???

(not) working example below:

julia> for i in [m["max_age"],m["type_id"]]
       i = Int.(i)
       end

julia> m["type_id"]
5×2 Array{Float64,2}:
 1.0  2.0
 0.0  1.0
 1.0  2.0
 1.0  3.0
 0.0  3.0

julia> m["type_id"] = Int.(m["type_id"])
5×2 Array{Int64,2}:
 1  2
 0  1
 1  2
 1  3
 0  3

Do

for i in [m["Array1"], m["Array2"], m["Array3"]]
    i .= Int.(i)
end

instead.

Note the dot in the assignment.

Also see my recent post about bindings/labels.

1 Like

Didn’t work :frowning:

ERROR: LoadError: MethodError: no method matching copyto!(::Float64, ::Base.Broadcast.Broadcasted{Base.Broadcast.DefaultArrayStyle{0},Tuple{},Type{Int64},Tuple{Float64}})
Closest candidates are:
  copyto!(::AbstractArray, ::Base.Broadcast.Broadcasted{var"#s826",Axes,F,Args} where Args<:Tuple where F where Axes where var"#s826"<:Base.Broadcast.AbstractArrayStyle{0}) at broadcast.jl:889
  copyto!(::AbstractArray, ::Base.Broadcast.Broadcasted) at broadcast.jl:886
  copyto!(::AbstractArray, ::Any) at abstractarray.jl:730

Weird, as it works when I write them out line for line (without the dot in the assignment), as in my above post…

Ah, of course, my bad, the type of the Array is concrete and you cannot change its contents this way, you really need to allocate a new Array. The solution then is:

for i in ("Array1", "Array2", "Array3")
    m[i] = Int.(m[i])
end

You need to change to what m is pointing to, so you need to change it some way. This ends up in what I say in my post. There are no boxes there. i is just a name, you create a whole new array with Int.(i), and you change i to refer to it; but i is just a label, it is not a box, changing what i refer to will not update anything, it is not a memory position that is shared by m.

2 Likes

Works perfect! Requires even less text too

Thanks, Henrique!