Sorting rows in pandas DataFrame (original) (raw)
Last Updated : 06 Jan, 2019
Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). We often need to do certain operations on both rows and column while handling the data.
Let’s see how to sort rows in pandas DataFrame.
Code #1: Sorting rows by Science
import
pandas as pd
data
=
{
'name'
: [
'Simon'
,
'Marsh'
,
'Gaurav'
,
'Alex'
,
'Selena'
],
`` 'Maths'
: [
8
,
5
,
6
,
9
,
7
],
`` 'Science'
: [
7
,
9
,
5
,
4
,
7
],
`` 'English'
: [
7
,
4
,
7
,
6
,
8
]}
df
=
pd.DataFrame(data)
a
=
df.sort_values(by
=
'Science'
, ascending
=
0
)
print
(
"Sorting rows by Science:\n \n"
, a)
Output:
Sorting rows by Science:
English Maths Science name
1 4 5 9 Marsh 0 7 8 7 Simon 4 8 7 7 Selena 2 7 6 5 Gaurav 3 6 9 4 Alex
Code #2: Sort rows by Maths and then by English.
import
pandas as pd
data
=
{
'name'
: [
'Simon'
,
'Marsh'
,
'Gaurav'
,
'Alex'
,
'Selena'
],
`` 'Maths'
: [
8
,
5
,
6
,
9
,
7
],
`` 'Science'
: [
7
,
9
,
5
,
4
,
7
],
`` 'English'
: [
7
,
4
,
7
,
6
,
8
]}
df
=
pd.DataFrame(data)
b
=
df.sort_values(by
=
[
'Maths'
,
'English'
])
print
(
"Sort rows by Maths and then by English: \n\n"
, b)
Output:
Sort rows by Maths and then by English:
English Maths Science name
1 4 5 9 Marsh 2 7 6 5 Gaurav 4 8 7 7 Selena 0 7 8 7 Simon 3 6 9 4 Alex
Code #3: If you want missing values first.
import
pandas as pd
data
=
{
'name'
: [
'Simon'
,
'Marsh'
,
'Gaurav'
,
'Alex'
,
'Selena'
],
`` 'Maths'
: [
8
,
5
,
6
,
9
,
7
],
`` 'Science'
: [
7
,
9
,
5
,
4
,
7
],
`` 'English'
: [
7
,
4
,
7
,
6
,
8
]}
df
=
pd.DataFrame(data)
a
=
df.sort_values(by
=
'Science'
, na_position
=
'first'
)
print
(a)
Output:
English Maths Science name 3 6 9 4 Alex 2 7 6 5 Gaurav 0 7 8 7 Simon 4 8 7 7 Selena 1 4 5 9 Marsh
As there are no missing values in this example this will produce same output as the above one, but sorted in ascending order.
Similar Reads
- Pandas Exercises and Programs Pandas is an open-source Python Library that is made mainly for working with relational or labelled data both easily and intuitively. This Python library is built on top of the NumPy library, providing various operations and data structures for manipulating numerical data and time series. Pandas is 6 min read
- Different ways to create Pandas Dataframe It is the most commonly used Pandas object. The pd.DataFrame() function is used to create a DataFrame in Pandas. There are several ways to create a Pandas Dataframe in Python. Example: Creating a DataFrame from a Dictionary [GFGTABS] Python import pandas as pd # initialize data of lists. data = { 7 min read