logo_learn_stats

Kind DataFrame via Each Index and Column

Posted on
banner 336x280

You’ll be able to worth please see syntax to type a pandas DataFrame via each index and column:

df = df.sort_values(via = ['column_name', 'index'], ascending = [False, True])

Refer to examples display tips on how to worth this syntax in follow.

banner 468x60

Examples: Kind DataFrame via Each Index and Column

Refer to code presentations tips on how to type a pandas DataFrame via the column named issues and next via the index column:

import pandas as pd

#manufacture DataFrame
df = pd.DataFrame({'identity': [1, 2, 3, 4, 5, 6, 7, 8],
                   'issues': [25, 15, 15, 14, 20, 20, 25, 29],
                   'assists': [5, 7, 7, 9, 12, 9, 9, 4],
                   'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]}).set_index('identity')

#view first few rows
df.head()

	issues	assists	rebounds
identity			
1	25	5	11
2	15	7	8
3	15	7	10
4	14	9	6
5	20	12	6

#type via issues and next via index
df.sort_values(via = ['points', 'id'], ascending = [False, True])

	issues	assists	rebounds
identity			
8	29	4	12
1	25	5	11
7	25	9	9
5	20	12	6
6	20	9	5
2	15	7	8
3	15	7	10
4	14	9	6

The ensuing DataFrame is looked after via issues in descending line and next via the index in ascending line (if there occur to be two avid gamers who rating the similar collection of issues).

Be aware that if we don’t worth the ascending argument, next each and every column will worth ascending because the default sorting mode:

#type via issues and next via index
df.sort_values(via = ['points', 'id'])

        issues	assists	rebounds
identity			
4	14	9	6
2	15	7	8
3	15	7	10
5	20	12	6
6	20	9	5
1	25	5	11
7	25	9	9
8	29	4	12

If the index column is lately no longer named, you’ll rename it and next type accordingly:

#type via issues and next via index
df.rename_axis('index').sort_values(via = ['points', 'id'])

        issues	assists	rebounds
identity			
4	14	9	6
2	15	7	8
3	15	7	10
5	20	12	6
6	20	9	5
1	25	5	11
7	25	9	9
8	29	4	12

Spare Sources

Pandas: Tips on how to Kind Columns via Title
Pandas: Kind DataFrame via Past
Pandas: Tips on how to Loose Reproduction Rows

banner 336x280

Leave a Reply

Your email address will not be published. Required fields are marked *