PowerShell: How to Select Top N Items from Each Group


Often you may want to select the top N items from each group in an object in PowerShell.

You can use the following syntax to do so:

$my_data | Group-Object team | ForEach-Object {$_.group[0..2]}

This particular example selects the top 3 items from each group of the object named $my_data, which has been grouped by the team property.

Here is what the various commands do:

  • Group-Object team: Group the rows in the $my_data object based on the team property
  • ForEach-Object: Specifies an action to perform on each group
  • $_: Retrieves the current row in the ForEach-Object loop
  • group[0..2]: Retrieves items in index positions 0 through 2 (i.e. the first 3 items) from the current row

The following example shows how to use this syntax in practice.

Example: Select Top N Items from Each Group in PowerShell

Suppose that we have a file named nba_data.csv that contains information about various basketball players.

We can use the following syntax to import this CSV file into an object named $my_data:

$my_data = Import-Csv nba_data.csv

The following screenshot shows how to use this syntax in practice:

Suppose that we would like to select the top 3 rows from each unique value in the team column.

We can use the following syntax to do so:

$my_data | Group-Object team | ForEach-Object {$_.group[0..2]}

The following screenshot shows how to use this syntax in practice:

PowerShell select top N items from each group

Notice that this returns the top 3 rows for each team.

To return a different number of rows for each group, simply change the 2 to a different value.

For example, you could use $_.group[0..4] to instead return the top 5 rows from each group.

Note: You can find the complete documentation for the Group-Object cmdlet in PowerShell here.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Check if Object has Specific Property
PowerShell: How to List All Object Properties
PowerShell: How to Use Group-Object with Multiple Properties
PowerShell: How to Use Sort-Object with Multiple Properties

Leave a Reply