Morpheu5
Morpheu5

Reputation: 2801

Concatenate Julia DataFrames adding a categorical column

Say I have the following

a = DataFrame(x = [1,2,3,4], y = [10,20,30,40])
b = DataFrame(x = [1,2,3,4], y = [50,60,70,80])

is there a way of getting [a;b] with an additional categorical column to obtain something like the following?

8×3 DataFrames.DataFrame
│ Row │ x │ y  │ c │
├─────┼───┼────┼───┤
│ 1   │ 1 │ 10 │ 1 │
│ 2   │ 2 │ 20 │ 1 │
│ 3   │ 3 │ 30 │ 1 │
│ 4   │ 4 │ 40 │ 1 │
│ 5   │ 1 │ 50 │ 2 │
│ 6   │ 2 │ 60 │ 2 │
│ 7   │ 3 │ 70 │ 2 │
│ 8   │ 4 │ 80 │ 2 │

For two dataframes, something like

using DataFramesMeta
[@transform(a, c = 1); @transform(b, c = 2)]

works, but what if I have more than a few DataFrames?

Upvotes: 1

Views: 152

Answers (1)

Liso
Liso

Reputation: 2260

You could use enumerate if you like to create result from array of DataFrames. For example:

l = [a,b]
vcat([transform(x,c=i) for (i,x) in enumerate(l)])

Upvotes: 1

Related Questions