The order of columns refers to the horizontal sequence in which the column names are created.
In the above example, the order of columns is Peter -> Harry -> Tom -> Jhon.
Sometimes we might need to rearrange this sequence. Pandas allow us to rearrange the order of columns using the loc Property.
pandas.DataFrame.loc Property
It is usually used for selecting rows and columns with the help of their names, but when it comes to rearrange the order of columns, this method is beneficial in more than one way. We can rearrange the order of all the columns or we can rearrange those columns that we want. It takes two arguments, the number of rows and the number of columns. Defining a colon (:) means selecting all the rows followed by a comma and a list of rearranged column names is the actual syntax to accomplish the task.
Syntax:
property DataFrame.loc
# Example
df.loc[:,['col_name','col_name','col_name','col_name']]
Example:
Output:
Explanation:
In the above example, we have passed a list of column names with the new sequence. An important point is that we will pass the list after defining the number of rows. Here, we have selected all the rows.
need an explanation for this answer? contact us directly to get an explanation for this answer