代码之家  ›  专栏  ›  技术社区  ›  Antonello

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

  •  0
  • Antonello  · 技术社区  · 7 年前

    我在julia中有一个包含数百列的数据帧,我想在第一列之后插入一列。

    例如,在此数据帧中:

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

    我想插入一列 area 之后 colour ,但没有特别提到 shape border (在我的实际案例中是数百个不同的列)。

    df[:area] = [1,2]
    

    在这个例子中,我可以使用 形状 边境 )以下内容:

    df = df[[:colour, :area, :shape, :border]] # with specific reference to shape and border names
    
    2 回复  |  直到 7 年前
        1
  •  6
  •   张实唯    7 年前

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

    using DataFrames
    
    df = DataFrame(
      colour = ["green","blue"],
      shape = ["circle", "triangle"],
      border = ["dotted", "line"]
    )
    
    insert!(df, 3, [1,2], :area)
    

    在哪里? 3 是插入后新列的预期索引, [1,2] 是它的内容,而且 :area 是名字。您可以通过键入 ?insert! 在REPL中加载 DataFrames 包裹。

    值得注意的是 ! 是函数名的一部分。 It's a Julia convention 以指示函数将改变其参数。

        2
  •  0
  •   Antonello    7 年前

    在提出这个问题的同时,我也找到了一个解决办法(这是常有的事)。 我还是把这个问题贴在这里(为我自己)和其他人记住。

    在“添加”新列之前保存列名就足够了:

    df = DataFrame(
      colour = ["green","blue"],
      shape = ["circle", "triangle"],
      border = ["dotted", "line"]
    )
    dfnames = names(df)
    df[:area] = [1,2]
    
    df = df[vcat(dfnames[1:1],:area,dfnames[2:end])]