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:
python912DataFrame.sort_values(by = 'column_name', inplace = True)
If we want to perform descending, we have to turn off the ascending
parameter.
python912DataFrame.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 isNone
.
Uppgift
Swipe to start coding
Now we are going to practice sorting. We will sort 2 different DataFrame columns using ascending and descending sorting.
- Import the
pandas
using thepd
alias. - Perform an ascending sorting by the
'price'
column. - Perform a descending sorting by the
'user_id'
column.
Lösning
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 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?
Tack för dina kommentarer!
Avsnitt 3. Kapitel 4
single
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 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
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal