Home Β» Julia Β» How to Sort DataFrame in Julia?

How to Sort DataFrame in Julia?

To sort a dataframe in Julia, you can use the sort function from the DataFrames package. The sort function allows you to sort the rows of a dataframe by one or more columns.

Sorting DataFrame in Julia Examples

Here is an example of how to use the sort function to sort a dataframe by a single column:

using DataFrames

# Create a sample dataframe
df = DataFrame(A = [3, 1, 2], B = ["c", "a", "b"])

# Sort the dataframe by column A
sorted_df = sort(df, [:A])

# Print the sorted dataframe
println(sorted_df)

The output of this code will be:

3Γ—2 DataFrame
β”‚ Row β”‚ A    β”‚ B    β”‚
β”‚     β”‚ Int64 β”‚ String β”‚
β”œβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€
β”‚ 1   β”‚ 1     β”‚ a     β”‚
β”‚ 2   β”‚ 2     β”‚ b     β”‚
β”‚ 3   β”‚ 3     β”‚ c     β”‚

You can also use the sort function to sort the dataframe by multiple columns. For example, to sort the dataframe by column A and then by column B, you can do the following:

using DataFrames

# Create a sample dataframe
df = DataFrame(A = [3, 1, 2], B = ["c", "a", "b"])

# Sort the dataframe by column A and then by column B
sorted_df = sort(df, [:A, :B])

# Print the sorted dataframe
println(sorted_df)

The output of this code will be:

3Γ—2 DataFrame
β”‚ Row β”‚ A    β”‚ B    β”‚
β”‚     β”‚ Int64 β”‚ String β”‚
β”œβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€
β”‚ 1   β”‚ 1     β”‚ a     β”‚
β”‚ 2   β”‚ 2     β”‚ b     β”‚
β”‚ 3   β”‚ 3     β”‚ c     β”‚

By default, the sort function sorts the data in ascending order. If you want to sort the data in descending order, you can pass the rev = true keyword argument to the sort function. For example:

using DataFrames

# Create a sample dataframe
df = DataFrame(A = [3, 1, 2], B = ["c", "a", "b"])

# Sort the dataframe by column A in descending order
sorted_df = sort(df, [:A], rev = true)

# Print the sorted dataframe
println(sorted_df)

The output of this code will be:

3Γ—2 DataFrame
β”‚ Row β”‚ A    β”‚ B    β”‚
β”‚     β”‚ Int64 β”‚ String β”‚
β”œβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€
β”‚ 1   β”‚ 3     β”‚ c     β”‚
β”‚ 2   β”‚ 2     β”‚ b     β”‚
β”‚ 3   β”‚ 1     β”‚ a     β”‚

Related:

  1. Export DataFrame to Excel in Julia
  2. Convert Array to DataFrame in Julia
  3. How to Create DataFrame in Julia?