How to change data type of Julia array from "Any" to "Float64"?

Is there a function in Julia that returns a copy of an array of the desired type, i.e. equivalent of numpys astype function ? I have an array of type "Any" and you want to convert it to a Float array. I tried:

new_array = Float64(array) 

but i get the following error

 LoadError: MethodError: `convert` has no method matching convert(::Type{Float64}, ::Array{Any,2}) This may have arisen from a call to the constructor Float64(...), since type constructors fall back to convert methods. Closest candidates are: call{T}(::Type{T}, ::Any) convert(::Type{Float64}, !Matched::Int8) convert(::Type{Float64}, !Matched::Int16) ... while loading In[140], in expression starting on line 1 in call at essentials.jl:56 

I can simply write a function that goes through the array and returns a float value for each element, but I find it a bit strange if there is no built-in method for this.

+8
arrays julia-lang
source share
4 answers

Use convert . Note the syntax that I used for the first array; if you know what you want before creating the array, you can declare the type in front of the square brackets. Any just as easily could be replaced with Float64 and eliminated the need for the convert function.

 julia> a = Any[1.2, 3, 7] 3-element Array{Any,1}: 1.2 3 7 julia> convert(Array{Float64,1}, a) 3-element Array{Float64,1}: 1.2 3.0 7.0 
+11
source share

You can use:

new_array = Array{Float64}(array)

+7
source share

The answers of Daniel and Randy are solid, I just add another way that I like because it can make more complex iterative cases relatively short. However, this is not as effective as the other answers, which are more specifically related to the conversion / type declaration. But since the syntax can be fairly easily extended to another use case, it’s worth adding:

 a = Array{Any,1}(rand(1000)) f = [float(a[i]) for i = 1:size(a,1)] 
+1
source share

You can also use the broadcast operator . :

 a = Any[1.2, 3, 7] Float64.(a) 
+1
source share

All Articles