# How to sample rows from a dataframe?

**URL:** <https://discourse.julialang.org/t/how-to-sample-rows-from-a-dataframe/19782>\
**Category:** New to Julia\
**Created:** [January 18, 2019, 1:39pm UTC](https://discourse.julialang.org/t/how-to-sample-rows-from-a-dataframe/19782 "2019-01-18T13:39:49Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Juan](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/juan/32/7657_2.png) [@Juan](https://discourse.julialang.org/u/Juan)\
**Post date:** [January 18, 2019, 1:39pm UTC](https://discourse.julialang.org/t/how-to-sample-rows-from-a-dataframe/19782/1 "2019-01-18T13:39:49Z")

</div>

Hello.

I’ve created a dataframe by reading a very long csv file.

Now I would like to create another smaller dataframe with the same columns but with a few rows sampled randomly (without replacement) from the original.

Say we have this toy example and we want to create a new one with 3 rows. I’ve tried several alternatives.

```julia
myDF = DataFrame(A = 1:10, B = 21:30)
sample(myDF, 3) # doesn't work
rand(myDF, 3) # doesn't work
randsubseq(myDF, 3) # doesn't work
myDF[sample(1:10,3),:] # doesn't work
myDF[rand(1:(size(myDF,1)),3),:] # it works 

```

```julia
newDF = myDF[rand(1:(size(myDF,1)),3),:] 
3×2 DataFrame
│ Row │ A │ B │
│ │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1 │ 2 │ 9 │
│ 2 │ 4 │ 7 │
│ 3 │ 10 │ 1 │

```

Is it the best way to do it?  
How do you do it?

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [January 18, 2019, 2:00pm UTC](https://discourse.julialang.org/t/how-to-sample-rows-from-a-dataframe/19782/2 "2019-01-18T14:00:10Z")

</div>

You can use `StatsBase.sample` to sample without replacement, and (optionally) keep the order:

```julia
using StatsBase, DataFrames
myDF = DataFrame(A = 1:10, B = 21:30)
myDF[sample(axes(myDF, 1), 3; replace = false, ordered = true), :]

```

---

<div class="post-metadata">

**Author:** ![bkamins](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bkamins/32/208538_2.png) [@bkamins](https://discourse.julialang.org/u/bkamins)\
**Post date:** [January 18, 2019, 2:28pm UTC](https://discourse.julialang.org/t/how-to-sample-rows-from-a-dataframe/19782/3 "2019-01-18T14:28:05Z")

</div>

And if you original `DataFrame` would be large (like millions of rows and hundreds of columns) you can use `view(myDF, rows, :)`, where `rows` is the result from `sample` as @Tamas_Papp explained.
