Adding a new row to a DataFrame


#1

It’s quite surprising that the DataFrames package documentation doesn’t provide a canonical way of adding a new record to a df. On the web I see approaches using push! append! vcat! and @data macros. Could someone help me out?


#2

Try this : create an array of the same length of your dataframe columns and then use
df[:colname]=array

 julia> df
5x4 DataFrames.DataFrame
| Row | a | b | c | d |
|-----|---|----|----|----|
| 1 | 1 | 7 | 10 | 20 |
| 2 | 2 | 8 | 11 | 21 |
| 3 | 3 | 9 | 12 | 22 |
| 4 | 4 | 10 | 13 | 23 |
| 5 | 5 | 11 | 14 | 24 |

julia> df[:M1]=m1
5-element Array{Float16,1}:
 4.0
 5.0
 6.0
 7.0
 8.0

julia> df
5x5 DataFrames.DataFrame
| Row | a | b | c | d | M1 |
|-----|---|----|----|----|-----|
| 1 | 1 | 7 | 10 | 20 | 4.0 |
| 2 | 2 | 8 | 11 | 21 | 5.0 |
| 3 | 3 | 9 | 12 | 22 | 6.0 |
| 4 | 4 | 10 | 13 | 23 | 7.0 |
| 5 | 5 | 11 | 14 | 24 | 8.0 |

#3

To add a row, you can merge 2 dataframes :

 julia> df = DataFrame(A = 1:4, B = ["M", "F", "F", "M"])
4×2 DataFrames.DataFrame
│ Row │ A │ B   │
├─────┼───┼─────┤
│ 1   │ 1 │ "M" │
│ 2   │ 2 │ "F" │
│ 3   │ 3 │ "F" │
│ 4   │ 4 │ "M" │

julia> df2 = DataFrame(A = 6, B = ["F"])
1×2 DataFrames.DataFrame
│ Row │ A │ B   │
├─────┼───┼─────┤
│ 1   │ 6 │ "F" │

julia> append!(df,df2)
5×2 DataFrames.DataFrame
│ Row │ A │ B   │
├─────┼───┼─────┤
│ 1   │ 1 │ "M" │
│ 2   │ 2 │ "F" │
│ 3   │ 3 │ "F" │
│ 4   │ 4 │ "M" │
│ 5   │ 6 │ "F" │

Append one line to similar DataFrame gives eltype error
#4

Another solution using push!() :

 julia> df = DataFrame(A = 1:4, B = ["M", "F", "F", "M"])
4×2 DataFrames.DataFrame
│ Row │ A │ B   │
├─────┼───┼─────┤
│ 1   │ 1 │ "M" │
│ 2   │ 2 │ "F" │
│ 3   │ 3 │ "F" │
│ 4   │ 4 │ "M" │

julia> push!(df,[6 "F"])

julia> df
5×2 DataFrames.DataFrame
│ Row │ A │ B   │
├─────┼───┼─────┤
│ 1   │ 1 │ "M" │
│ 2   │ 2 │ "F" │
│ 3   │ 3 │ "F" │
│ 4   │ 4 │ "M" │
│ 5   │ 6 │ "F" │