How to convert a dataframe into a 1-D vector, line by line?

Hi,

I have a dataframe looking like:

using DataFrames

df = DataFrame(a=1:4, b=5:8)
4×2 DataFrame
 Row │ a      b     
     │ Int64  Int64 
─────┼──────────────
   1 │     1      5
   2 │     2      6
   3 │     3      7
   4 │     4      8

From that, I would like to create a vector/array like:

[1, 5, 2, 6, 3, 7, 4, 8]

Tried many hcat, vcat, values etc. combinations without success…

julia> v = Int[]
Int64[]

julia> for i in eachindex(df.a, df.b)
           push!(v, df.a[i])
           push!(v, df.b[i])
       end

julia> v
8-element Vector{Int64}:
 1
 5
 2
 6
 3
 7
 4
 8
1 Like

I’m not sure about performance, but here’s a one-liner:

df |> Matrix |> vec

and if you need the specific ordering of the elements:

vec(Matrix(df)')

# or df |> Matrix |> transpose |> vec
1 Like

Thanks everyone !

julia> vcat(df.a, df.b)
8-element Vector{Int64}:
 1
 2
 3
 4
 5
 6
 7
 8

Ahem! Didn’t read the Q carefully enough!

other ways

vcat(eachcol(permutedims(df))...)

stack(permutedims(df),:).value


r,c=size(df)
vc=Vector{typeof(df[1,1])}(undef,r*c)
idx=0
for i in 1:r, j in 1:c
    vc[idx+=1]=df[i,j]
end
vc
Matrix(df)'[:]
1 Like

:man_shrugging:

julia> df |> eachrow |> Iterators.flatten |> collect
8-element Vector{Int64}:
 1
 5
 2
 6
 3
 7
 4
 8