Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Sorting Data | Explore Dataset
Introduction to Python for Data Analysis

book
Sorting Data

We need sorting for ease of work.

We can sort our data in 2 ways: ascending sorting and descending sorting.

To perform the ascending sorting, use the following code:

python
DataFrame.sort_values(by = 'column_name', inplace = True)

If we want to perform descending, we have to turn off the ascending parameter.

python
DataFrame.sort_values(by = 'column_name', inplace = True, ascending = False)

If the parameter inplace is set to True (inplace = True), it will perform the operation inplace. Modify the original DataFrame itself. The return type is None.

Uppgift

Swipe to start coding

Now we are going to practice sorting. We will sort 2 different DataFrame columns using ascending and descending sorting.

  1. Import the pandas using the pd alias.
  2. Perform an ascending sorting by the 'price' column.
  3. Perform a descending sorting by the 'user_id' column.

Lösning

# Import the pandas
import pandas as pd

# Reading the csv file using the df variable
df = pd.read_csv('https://codefinity-content-media.s3.eu-west-1.amazonaws.com/783d7288-e86b-4b89-9966-a2fe97995277/section_2_dataset_upd.csv')

# Ascending sorting by the 'price' column
df.sort_values(by = 'price', inplace = True)
print(df.head())

# Rereading the file as the previous one has been changed
df = pd.read_csv('https://codefinity-content-media.s3.eu-west-1.amazonaws.com/783d7288-e86b-4b89-9966-a2fe97995277/section_2_dataset_upd.csv')

# Descending sorting by the 'user_id' column
df.sort_values(by = 'user_id', inplace = True, ascending = False)
print(df.head())

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 3. Kapitel 4
single

single

# Import the pandas
___

# Reading the csv file using the df variable
df = pd.read_csv('https://codefinity-content-media.s3.eu-west-1.amazonaws.com/783d7288-e86b-4b89-9966-a2fe97995277/section_2_dataset_upd.csv')

# Ascending sorting by the 'price' column
df.___(by = '___', inplace = True)
print(df.head())

# Rereading the file as the previous one has been changed
df = pd.read_csv('https://codefinity-content-media.s3.eu-west-1.amazonaws.com/783d7288-e86b-4b89-9966-a2fe97995277/section_2_dataset_upd.csv')

# Descending sorting by the 'user_id' column
___.___(___ = 'user_id', inplace = True, ___ = False)
print(df.head())

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

some-alt