如何在特定位置的julia DataFrame中插入列(不引用现有列名)

Ant*_*llo 0 dataframe julia

我在Julia中有一个包含数百列的DataFrame,我想在第一列之后插入一列.

例如,在此DataFrame中:

df = DataFrame(
  colour = ["green","blue"],
  shape = ["circle", "triangle"],
  border = ["dotted", "line"]
)
Run Code Online (Sandbox Code Playgroud)

我想area在之后插入一个列colour,但没有具体指向shapeborder(在我的实际情况下是数百个不同的列).

df[:area] = [1,2]
Run Code Online (Sandbox Code Playgroud)

在这个例子中,我可以使用(但具体指shapeborder):

df = df[[:colour, :area, :shape, :border]] # with specific reference to shape and border names
Run Code Online (Sandbox Code Playgroud)

张实唯*_*张实唯 6

好吧,恭喜你找到了一个自己的解决方法,但有一个内置函数在语义上更清晰,可能更快一点:

using DataFrames

df = DataFrame(
  colour = ["green","blue"],
  shape = ["circle", "triangle"],
  border = ["dotted", "line"]
)

insert!(df, 3, [1,2], :area)
Run Code Online (Sandbox Code Playgroud)

3插入后新列的预期索引在哪里,[1,2]是其内容,并且:area是名称.?insert!加载DataFrames包后,您可以通过键入REPL 找到更详细的文档.

值得注意的是,它是!函数名称的一部分.这是一个Julia约定,表明函数将改变它的参数.

  • 现在是 `insertcols!`,例如:`insertcols!(df, 3, :area => [1, 2] )` (8认同)

Uki*_*cas 5

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
Run Code Online (Sandbox Code Playgroud)