Newbie Syntax Help: Colon in Index Syntax ---> sepal_length_column = iris[:Sepal_Length]


#1

Hello:

I need some help to a doc page for a particular syntax (keep in mind I am a c programmer…) I have seen code that looks like this:

sepal_length_column = iris[:Sepal_Length]

In the case above, it was an example from the dataframes module. What is the syntax in the square brackets? It is being used like array interation but with a string. I have not seen this type of syntax in other languages. I have also seen in in the PyPlot library. here is an example:

ax[:spines][“top”]:set_color # Remove the top axis boundary

In this case :spines looks like it is some sort of binding to a class member in matplotlib.

A pointer to what this syntax is called would be helpful.

Thanks.


#2

the square bracket syntax [] is just shorthand for the function getindex defined in Base.

Think of a DataFrame as an array of arrays, each one for a column. Then they define new methods for the function getindex to have the desired behavior. You can do this too.

struct A 
     x::Vector
end

import Base.getindex

function getindex(a::A, n)
     getindex(A.x, n)
end

x = ["here", "there", "everywhere"]

a = A(x)

a[1]

> "here"

#3

prefixing text with a colon gives a Symbol, e.g. :foo, :bar. The Dataframes package allows a DataFrame to be indexed with a Symbol to refer to the column with that name.

The PyCall package allows python libraries to be called from Julia code, but translates a obj.field in Python into obj[:field] in Julia. see the usage section of the docs for details.

also - please surround quoted code with back-ticks so it gets nice syntax highlighting and is displayed in a fixed-width font. Single backticks are for in-line code like this, and triple quotes are used for longer code:

like this

#4

Thanks for the replies. Very Helpful!


#5

FWIW on Julia 0.7 one can also write iris.Sepal_Length instead.


#6

FWIW on Julia 0.7 one can also write iris.Sepal_Length instead, which calls the getproperty/setproperty! functions.


#7

There is a very good explanation about what is a symbol on stackoverflow by Stefan Karpinski. Link: https://stackoverflow.com/questions/23480722/what-is-a-symbol-in-julia.