Julia: How to convert `Between(:col1, :col2)` to column index for DataFrames.DataFrame?

Viewed 36

Consider

using DataFrames
df=DataFrame(a=1:3, b=1:3, c=1:3)

and suppose I want to turn Between(:b, :c) into column indices, which should return [2, 3]?

I can select those columns extract the names and then call columnindex but that's not very elegant.

1 Answers

Use:

names(df, Between(:b, :c))

to get the selected column names and:

columnindex.(Ref(df), names(df, Between(:b, :c)))

or (a longer but easier to read)

[columnindex(df, n) for n in names(df, Between(:b, :c))]

to get column numbers.

If you wanted something faster that is internal (i.e. not guaranteed to be working in the long term and not documented; though it it unlikely to be changed - so it is relatively safe to use):

DataFrames.index(df)[Between(:b, :c)]

A small difference between getindex on DataFrames.index and using columnindex is that:

  • columnindex will return 0 for non-existent column (while getindex on DataFrames.index errors)
  • you cannot pass an integer to columnindex, while you can pass it to getindex on DataFrames.index
Related