How to get a DataFrame of first n elements and last n elements from a sorted DataFrame

I have the following CSV Data which is loaded into a DataFrame:

import Foundation
import TabularData

func main() {
  let csv = """
    Text,Value
    Frog,47
    Duck,11
    Horse, 11
    Bee, 12
    Spider,55
    Flower,1
    Tree,100
    """
  var df = try! DataFrame(csvData: Data(csv.utf8))
  df = df.sorted(on: "Value", order: .descending)

   
  print(df)
  /*Prints
   ┏━━━┳━━━━━━━━━━┳━━━━━━━━━━┓
   ┃   ┃ Text     ┃ Value    ┃
   ┃   ┃ <String> ┃ <Double> ┃
   ┡━━━╇━━━━━━━━━━╇━━━━━━━━━━┩
   │ 0 │ Tree     │  100,0   │
   │ 1 │ Spider   │   55,0   │
   │ 2 │ Frog     │   47,0   │
   │ 3 │ Bee      │   12,0   │
   │ 4 │ Duck     │   11,0.  │
   │ 5 │ Horse    │   11,0   │
   │ 6 │ Flower   │   1,0    │
   └───┴──────────┴──────────┘
   
   */
     
}

main()

I want, for example, only the first two and last two elements from the DataFrame above:


┏━━━┳━━━━━━━━━━┳━━━━━━━━━━┓
┃   ┃ Text     ┃ Value    ┃
┃   ┃ <String> ┃ <Double> ┃
┡━━━╇━━━━━━━━━━╇━━━━━━━━━━┩
│ 0 │ Tree     │  100,0   │
│ 1 │ Spider   │   55,0   │
│ 2 │ Horse    │   11,0   │
│ 3 │ Flower   │   1,0    │
└───┴──────────┴──────────┘
Answered by DTS Engineer in 729754022

Thanks for posting a runnable example!

There’s probably a cleverer way to do this but the following certainly works:

var df2 = DataFrame(df.prefix(2))
df2.append(DataFrame(df.suffix(2)))
print(df2)

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Accepted Answer

Thanks for posting a runnable example!

There’s probably a cleverer way to do this but the following certainly works:

var df2 = DataFrame(df.prefix(2))
df2.append(DataFrame(df.suffix(2)))
print(df2)

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

How to get a DataFrame of first n elements and last n elements from a sorted DataFrame
 
 
Q