Adding a new row to a DataFrame

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?

1 Like

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 |
1 Like

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" │
5 Likes

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" │
9 Likes

What if I want to add certain rows, and in all the other rows, I only want to add 0?

maybe this works for you:

df = DataFrame(A = 1:4, B = ["M", "F", "F", "M"])
defaultRow = (A=0,B="0")
push!(df, (defaultRow...,A=1))
push!(df, (defaultRow...,B="hello"))
1 Like

I got that to work, this too.

df = DataFrame(A = 1:4, B = [“M”, “F”, “F”, “M”])
defaultRow = (A=0,B=“0”)
Macro d(a,b
ex=quote
push!(df, (defaultRow…,$a=$b))
end
end

@d(A,0)
@d(B,“Hello”)

sidenote: use a code block for code ^^ there’s a clickable button for it next to the text field. Alternatively use triple backticks as begin and end markers. Backtick: ` (not to be confused with forward tick ´ or apostroph ')

```
code
```
1 Like

This synrtax is currently not supported. Use df.M1 instead.

2 Likes