janitor.reorder_columns

janitor.reorder_columns(df: pandas.core.frame.DataFrame, column_order: Union[Iterable[str], pandas.core.indexes.base.Index, Hashable]) → pandas.core.frame.DataFrame[source]

Reorder DataFrame columns by specifying desired order as list of col names.

Columns not specified retain their order and follow after specified cols.

Validates column_order to ensure columns are all present in DataFrame.

This method does not mutate the original DataFrame.

Functional usage syntax:

Given DataFrame with column names col1, col2, col3:

df = reorder_columns(df, ['col2', 'col3'])

Method chaining syntax:

import pandas as pd
import janitor
df = pd.DataFrame(...).reorder_columns(['col2', 'col3'])

The column order of df is now col2, col3, col1.

Internally, this function uses DataFrame.reindex with copy=False to avoid unnecessary data duplication.

Parameters
  • dfDataFrame to reorder

  • column_order – A list of column names or Pandas Index specifying their order in the returned DataFrame.

Returns

A pandas DataFrame with reordered columns.

Raises

IndexError – if a column within column_order is not found within the DataFrame.