Sorting a DataFrame
Sorting: It refers to arranging values in a particular order. Ascending or Descending
Pandas makes available sort_values () and sort_index () functions for this purpose.
The values can be sorted on the basis of a specific column(s) and can be in ascending or descending order.
Syntax:
df.sort_values (by, ascending, inplace,na_position)
df.sort_values (by= [], ascending=, inplace=, na_position=)
“by” argument contains r column name(s) values.
by: Single/List of column names to sort Data Frame by.
if you specify the first argument by as a list, you can sort by multiple columns.
Ascending: Boolean value which sorts Data frame in ascending order if True.
Setting the ascending argument to False will sort the data in Descending
na_position: Takes two string input ‘last’ or ‘first’ to set position of Null values. Default is ‘last’.
If there is a missing value NaN, by default it is listed at the end.
Inplace: When inplace = True , the data is modified in place, which means it will return nothing and the dataframe is now updated. When inplace = False , which is the default, then the operation is performed and it returns a copy of the object. You then need to save it to something.
import pandas as pd
mydata={'code':[100,110,120,130,140],\
'ename':["Shaurya","Anil",None,"Kartik","Divyansh"],\
'Dept':["IT","Finance","IT","IT","HRD"],\
'salary':[34000,28500,15500,41000,17000],\
'status':["Regular","Regular","Contract","Regular",None]
}
emp=pd.DataFrame(mydata)
print(emp)
print("\n\n")
#print(emp.sort_values('ename',na_position="first",inplace=False))
print(emp.sort_values('ename',na_position="first",inplace=True))
print("\n\n")
print(emp)
Sorting on the basis of index
Only indices(rows (0) and columns (1) are sorted in ascending or descending order.
Syntax
df.sort_index (axis, ascending, inplace, na_position=)
no “by” argument because its works on index i.e 0 represents row-wise and 1 represents column- wise
axis=0
axis=1
sort by index labels
sort_values(axis=0)
sorting based on column labels
sort_values(axis=1)
print(emp.sort_index(axis=1,na_position="first",inplace=True,ascending=False))
Информация по комментариям в разработке