Basic Relocating

We wish to obtain a set of columns of a data frame, that contains some or all columns, sorted in a given order.

This section is organized as follows:

  • By Name: We refer to the columns whose location we wish to change by their name.
  • By Location: We refer to the columns whose location we wish to change by their location (integer) in the original data frame.

By Name

We wish to change the locations of the columns of a data frame by spelling out their names in the desired order.

df_2 = df.loc[:, ['col_3', 'col_1', 'col_4', 'col_2']]

Here is how this works:

  • To change the order of columns of a data frame, we simply select all columns by passing a list with the column names arranged in the desired order. See Basic Selecting.
  • If one or more columns are omitted from the list of column names passed to loc[], they will be excluded from the output data frame.
  • Columns that are not mentioned in the list passed to loc[] will be dropped. See Relative Relocating for how to relocate certain columns relative to the rest.

Alternative: via the Bracket Operator

df_2 = df[['col_3', 'col_1', 'col_4', 'col_2']]

Here is how this works:

  • We can pass to the bracket operator [] a list of column names specifying the desired column order.
  • While loc[] is the recommended approach for column selection by name because of its singular purpose unambiguous nature, in most common situations, the bracket [] operator can be used instead of loc[]. See Basic Selecting.

By Location

We wish to change the locations of the columns of a data frame by spelling out their numerical positions (in the original data frame) in the desired order.

df_2 = df.iloc[:, [2, 0, 3, 1]]

Here is how this works:

  • The order of the columns in the output data frame is determined by the order of the current column positions we provide to iloc[]. See Basic Selecting.
  • Column positions that are not mentioned in the list passed to iloc[] will be dropped. See Relative Relocating for how to relocate certain columns relative to the rest.
  • As a reminder, positions in Python start at 0.
PYTHON
I/O