How to reorder columns?

0212

To reorder columns in a pandas DataFrame, you can simply use indexing to specify the new order of the columns. Here’s how you can do it:

Example

import pandas as pd

# Sample DataFrame
data = {
    'A': [1, 2, 3],
    'B': [4, 5, 6],
    'C': [7, 8, 9]
}
df = pd.DataFrame(data)

# Original DataFrame
print("Original DataFrame:")
print(df)

# Reorder columns
new_order = ['C', 'A', 'B']
df_reordered = df[new_order]

# Reordered DataFrame
print("\nReordered DataFrame:")
print(df_reordered)

Explanation

  1. Create a DataFrame: We first create a sample DataFrame with columns 'A', 'B', and 'C'.
  2. Specify New Order: We define a list new_order that specifies the desired order of the columns.
  3. Reorder Columns: We create a new DataFrame df_reordered by indexing the original DataFrame with the new order.
  4. Display: Finally, we print the reordered DataFrame.

You can modify the new_order list to any order you prefer. If you have any further questions or need additional examples, let me know!

0 Comments

no data
Be the first to share your comment!