Hi,
I would like to copy (not a view) a column of dataframe inside the same dataframe.
E.g. to have:
julia> df = DataFrame(A=1:4, B=["A", "B", "C", "D"])
4×2 DataFrame
Row │ A B
│ Int64 String
─────┼───────────────
1 │ 1 A
2 │ 2 B
3 │ 3 C
4 │ 4 D
into, let’s say the “:new_col” containing the same elements as “:A”.
I’ve tried using
insertcols!(df, 3, copy(df.A), :new_col)
and some variants without success…
Do you mean this?
julia> df = DataFrame(A=1:4, B=["A", "B", "C", "D"])
4×2 DataFrame
Row │ A B
│ Int64 String
─────┼───────────────
1 │ 1 A
2 │ 2 B
3 │ 3 C
4 │ 4 D
julia> df.b_again = copy(df.B);
julia> df.b_again[2] = "E";
julia> df
4×3 DataFrame
Row │ A B b_again
│ Int64 String String
─────┼────────────────────────
1 │ 1 A A
2 │ 2 B E
3 │ 3 C C
4 │ 4 D D
2 Likes
You could write:
insertcols!(df, 3, :new_col => df.A)
which in this case is the same as:
insertcols!(df, :new_col => df.A)
1 Like
Also consider using the following syntaxes:
julia> df = DataFrame(A=1:4, B=["A", "B", "C", "D"])
4×2 DataFrame
Row │ A B
│ Int64 String
─────┼───────────────
1 │ 1 A
2 │ 2 B
3 │ 3 C
4 │ 4 D
julia> df[!, :C] = df.A
4-element Vector{Int64}:
1
2
3
4
julia> df
4×3 DataFrame
Row │ A B C
│ Int64 String Int64
─────┼──────────────────────
1 │ 1 A 1
2 │ 2 B 2
3 │ 3 C 3
4 │ 4 D 4
julia> df.C[3]
3
julia> df.C[3] = 33
33
julia> df
4×3 DataFrame
Row │ A B C
│ Int64 String Int64
─────┼──────────────────────
1 │ 1 A 1
2 │ 2 B 2
3 │ 33 C 33
4 │ 4 D 4
julia> df[:, :D] = df.A
4-element Vector{Int64}:
1
2
33
4
julia> df.D[3]=3
3
julia> df
4×4 DataFrame
Row │ A B C D
│ Int64 String Int64 Int64
─────┼─────────────────────────────
1 │ 1 A 1 1
2 │ 2 B 2 2
3 │ 33 C 33 3
4 │ 4 D 4 4
2 Likes