To reorder the columns in a Pandas dataframe, you can use the reindex()
function with the columns
parameter. This allows you to specify the order of the columns in the resulting dataframe, by providing a list of the column names in the desired order.
Here's an example of using the reindex()
function to reorder the columns in a Pandas dataframe:
import pandas as pd
# create a sample dataframe
df = pd.DataFrame({"A": [1, 2, 3],
"B": [4, 5, 6],
"C": [7, 8, 9]})
# reorder the columns in the dataframe
df_reordered = df.reindex(columns=["C", "B", "A"])
# display the result
print(df_reordered)
This will reorder the columns in the dataframe so that the C
column is first, followed by the B
column, and finally the A
column. The resulting dataframe will be displayed to the console. The output will be:
C B A
0 7 4 1
1 8 5 2
2 9 6 3
The reindex()
function allows you to specify the order of the columns in a dataframe by providing a list of the column names in the desired order.
This is a convenient way to rearrange the columns in a dataframe.
Related tutorials curated for you
How to convert a Pandas Index to a List
How to calculate the standard deviation in Pandas DataFrame
How to groupby mean in Pnadas
How to GroupBy Index in Pandas
Pandas read SQL
How to use pandas map() function
What is isna() in Pandas?
How to convert a series to a NumPy array in Pandas
What does factorize() do in Pandas?
How to find the mode in a Pandas DataFrame
How to get the absolute value for a column in Pandas
How to stack two Pandas DataFrames