Coding Ref

How to change the order of columns in Pandas

How to change the order of columns in Pandas

To change the order of columns in a Pandas DataFrame, you can use the reindex method.

This method takes a list of column names as an argument, and returns a new DataFrame with the columns in the specified order.

For example, consider the following DataFrame:

main.py
import pandas as pd

df = pd.DataFrame({
    'A': [1, 2, 3, 4, 5],
    'B': [10, 20, 30, 40, 50],
    'C': [100, 200, 300, 400, 500]
})

This DataFrame has three columns A, B, and C, with five rows of data.

To change the order of the columns in this DataFrame, you could do the following:

main.py
import pandas as pd

df = pd.DataFrame({
    'A': [1, 2, 3, 4, 5],
    'B': [10, 20, 30, 40, 50],
    'C': [100, 200, 300, 400, 500]
})

# Reorder the columns in the DataFrame
df = df.reindex(columns=['C', 'A', 'B'])

# Print the resulting DataFrame
print(df)

In the code above, the reindex method is used to specify the order of the columns in the DataFrame.

The columns argument is used to provide a list of column names in the desired order, which in this case is C, A, B.

The reindex method returns a new DataFrame with the columns in the specified order. In this case, the resulting DataFrame has the columns C, A, and B in that order.

You can also use the reindex method to rearrange the columns in a DataFrame by their current positions.

For example, if you wanted to move the B column to the first position, you could do the following:

main.py
import pandas as pd

df = pd.DataFrame({
    'A': [1, 2, 3, 4, 5],
    'B': [10, 20, 30, 40, 50],
    'C': [100, 200, 300, 400, 500]
})

# Reorder the columns in the DataFrame
df = df.reindex(columns=['B', 'C', 'A'])

# Print the resulting DataFrame
print(df)

In the code above, the reindex method is used to specify the order of the columns in the DataFrame.

The columns argument is used to provide a list of column names in the desired order, which in this case is B, C, A. The reindex method returns a new DataFrame with the columns in the specified order.

In this case, the resulting DataFrame has the columns B, C, and A in that order.

You'll also like

Related tutorials curated for you

    What is date_range() in Pandas?

    How to stack two Pandas DataFrames

    What is .notnull in Pandas?

    How to convert string to float in Pandas

    How to get the number of columns in a Pandas DataFrame

    How to join two DataFrames in Pandas

    fillna() in Pandas

    How to convert a Pandas Index to a List

    What does Count() do in Pandas?

    How to select multiple columns in Pandas

    How to read a TSV file in Pandas

    How to sort a series in Pandas