I have a DataFrame in Julia with hundreds of columns, and I would like to insert a column after the first one.
For example in this DataFrame:
df = DataFrame(
colour = ["green","blue"],
shape = ["circle", "triangle"],
border = ["dotted", "line"]
)
I would like to insert a column area
after colour
, but without referring specifically to shape
and border
(that in my real case are hundreds of different columns).
df[:area] = [1,2]
In this example I can use (but referring specifically to shape
and border
):
df = df[[:colour, :area, :shape, :border]] # with specific reference to shape and border names
Create an empty Julia DataFrame by enclosing column names and datatype of column inside DataFrame() function. Now you can add rows one by one using push!() function. This is like row binding.
You can simply create a data frame using the DataFrame() function. You can mention the columns and their values in between the brackets of the DataFrame() function as the argument and run it as shown below. Before this you have to tell Julia that you are going to use data frames by using the command 'using DataFrames'.
Update: This function has changed. See @DiegoJavierZea ’s comment.
Well, congratulate you found a workaround your self, but there is a built-in function that is semantically more clear and possibly a little bit faster:
using DataFrames
df = DataFrame(
colour = ["green","blue"],
shape = ["circle", "triangle"],
border = ["dotted", "line"]
)
insert!(df, 3, [1,2], :area)
Where 3
is the expected index for the new column after the insertion, [1,2]
is its content, and :area
is the name. You can find a more detailed document by typing ?insert!
in REPL after loading the DataFrames
package.
It is worth noting that the !
is a part of the function name. It's a Julia convention to indicate that the function will mutate its argument.
rows = size(df)[1] # tuple gives you (rows,columns) of the DataFrame
insertcols!(df, # DataFrame to be changed
1, # insert as column 1
:Day => 1:rows, # populate as "Day" with 1,2,3,..
makeunique=true) # if the name of the column exist, make is Day_1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With