Julia: Converting PyObject to an Array - julia

In Julia, I am calling a Python module pandas_datareader to download data from the web:
using PyCall
#pyimport datetime
#pyimport pandas_datareader.data as web
gdp = web.DataReader("GDPCA","fred",start=datetime.datetime(1929,1,1))
The variable gdp is a PyObject object. As such, I cannot manipulate it (take logs for example). How do I convert it to an array? I tried convert(Array{Float64,2},gdp), but it only crashes Julia.
Thanks!

The #pyimport macro is used to manipulate the Python objects in this case, pandas DataFrame, via the PyObject type. Given o::PyObject, o[:attribute] is equivalent to o.attribute in Python, with automatic type conversion. So the below snippet shows how to obtain a Julia array from a call to Python function,
julia> using PyCall
julia> #pyimport datetime
julia> gdp = web.DataReader("GDPCA","fred",start=datetime.datetime(1929,1,1))
julia> typeof(gdp)
PyCall.PyObject
julia> gdp[:values]
87x1 Array{Float64,2}:
1056.6
966.7
904.8
788.2
778.3
...

Related

Parametric functors in Julia

Starting 0.6 it is possible to create parametric methods in Julia using where syntax. According to the release notes of 0.6 version, where syntax
can be used anywhere a type is accepted
Now consider the following contrived example:
function (rng::R)() where {R <: Range}
return first(rng)
end
which, when I attempt to compile it, gives the following error:
ERROR: function type in method definition is not a type
So my question is what is the proper way to create parametric functors in Julia 0.6+?
Ohkay, I get what you are trying to do basically. To understand functors here is a short example code.
julia> struct Student
name::String
end
julia> function (::Student)()
println("Callable of Student Type!")
end
julia> object = Student("JuliaLang")
Student("JuliaLang")
julia> object()
Callable of Student Type!
but when I try to create the parametric functors, it throws out the error similar to yours!
julia> function (::T)() where {T <: Student}
println("Callable of Student Type!")
end
ERROR: function type in method definition is not a type
This problem is actually still OPEN as a issue as #gnimuc rightly pointed out.
You mix up two things
parametric methods e.q. julia> same_type(x::T, y::T) where {T} = true
function-like objects e.g. julia> function (p::Polynomial)(x) ... end
To my knowledge there is no "parametric function-like objects"
However, the following code should be the same of what you intend.
Julia> function (rng::Range)()
return first(rng)
end
cannot add methods to an abstract type
The current docu does not mention any limitation of function-like objects to concrete type, but unfortunately Julia doesn't accept it anyway.

How to use type using parametric typing

I am trying to use type using parametric typing But I get an Error. My julia version is 0.6.
Code:
type BasicRBC{T <: Real}
a::T
b::T
vce::Matrix{T}
matrix1::Matrix{T}
c::T
output::T
cons::T
vG::Vector{T}
end
Error:
invalid redefinition of constant BasicRBC
a,b,c,output and cons are Float64
matrix1 is Matrix
vG is Array
vce is [ 0.9 0.8 0.1]
You cannot modify a type in the same Julia session because Julia compiles things using the information about the exact type layout in order to make functions fast. Thus if you want to change type definitions, you need to refresh your workspace or restart Julia as #TasosPapastylianou said.– Chris Rackauckas

What is JuliaLang's equivalent to Python's sys.executable?

I would like to retrieve the path of the currently running Julia interpreter from Julia. In Python, this can be achieved with sys.executable.
Base.julia_cmd() is probably what you need. It returns the full command line that was used to invoke the current julia process, with the default options spelled out. Base.julia_exename() returns the name of the executable.
julia> Base.julia_cmd()
/Users/aviks/dev/julia/julia5/usr/bin/julia -Cnative -J/usr/lib/julia/sys.dylib --compile=yes --depwarn=yes
julia> Base.julia_exename()
"julia"
If you just want the location of the julia executable, try one of these:
julia> julia_bin_exe = joinpath(Base.Sys.BINDIR,Base.julia_exename())
"/home/mkitti/src/julia/usr/bin/julia"
julia> Base.julia_cmd()
`/home/mkitti/src/julia/usr/bin/julia -Cnative -J/home/mkitti/src/julia/usr/lib/julia/sys.so -g1`
julia> typeof(Base.julia_cmd())
Cmd
julia> Base.julia_cmd()[1]
"/home/mkitti/src/julia/usr/bin/julia"
julia> julia_bin_exe == Base.julia_cmd()[1]
true

Set axis origin using PyPlot plot in Julia

I am completely new to Julia. I am using the PyPlot package in Julia and am just trying to set my x and y axis origin to 0 and 0 respectively. At the moment it just chooses where the origin will be based on the values of the points I'm plotting.
plot(x1,y1,".")
xlabel("X1")
ylabel("Y1")
title("First Line")
grid("on")
I have tried the following but it doesn't work.
change matplotlib axis settings
Using PyPlot in Julia is different than matplotlib in Python. You are looking for the Julia equivalent of setting limits on axis. I've found this useful github repo that might be of use to you.
Here is how you can add custom limits to the y axis:
using PyPlot
x1 = rand(50, 1) .* 30 .+ 50
y1 = rand(50, 1) .* 30 .+ 100
plot(x1, y1)
# get the current axis argument of the plot
ax = gca()
# add new limits from 0 - 100
ax[:set_ylim]([0,100])
The syntax for using PyPlot in Julia is a bit different from Python.
This is a result of the fact that (currently) you cannot use obj.f() to access the method (function) f() inside an object obj in Julia, which PyPlot uses heavily.
To get around this, obj.f() in Python is replaced by obj[:f]() in Julia; note the :.
So ax.spines in Python becomes
ax[:spines]
in Julia.
As noted by the other poster, you must first do ax = gca() to store the current axis object in the variable ax.
If you do this at the Julia REPL or in a Jupyter notebook, you will see
julia> ax = gca()
PyObject <matplotlib.axes._subplots.AxesSubplot object at 0x31f854550>
julia> ax[:spines]
Dict{Any,Any} with 4 entries:
"left" => PyObject <matplotlib.spines.Spine object at 0x31f854c10>
"bottom" => PyObject <matplotlib.spines.Spine object at 0x31f854f50>
"right" => PyObject <matplotlib.spines.Spine object at 0x31f854dd0>
"top" => PyObject <matplotlib.spines.Spine object at 0x31f86e110>
showing that ax[:spines] is a dictionary. (I did not previously know about this. This is the advantage of having an interactive session -- you can just ask Julia what you need to know. This is called "introspection".)
Following the Python answer linked to in the original question, you then need to replace ax.spines['left'].set_position('zero') in Python by the following in Julia:
ax[:spines]["left"][:set_position]("zero")
Again, the set_position method inside the object ax[:spines]["left"] is called. Note also that strings in Julia must have ", not '.

Date not working in ipython notebook but works on julia REPL

using Dates
dateReported = map((x) -> string(x), df[:DateReported])
df[:DateOccurred] = map((x) -> if match(r"^((19|20)\d\d)(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])", x)!=nothing Date(x, DateFormat("yyyymmdd")) end, dateOccurred)
I am trying to change type of a dataframe column to Date from Int64.
The last statement returns an error
Date not defined
while loading In[18], in expression starting on line 1
in anonymous at In[18]:1
in map at /Users/ajkale/.julia/v0.3/DataArrays/src/datavector.jl:117
I am trying this in the ipython julia notebook. This works fine in the REPL though.
Dates was not part of the Julia standard library in 0.3. Since then, Julia 0.4 and now 0.5 have this baked into the standard library.
http://docs.julialang.org/en/latest/manual/dates/

Resources