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:
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:
loc[]
, they will be excluded from the output data frame.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:
[]
a list of column names specifying the desired column order.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.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:
iloc[]
. See Basic Selecting.iloc[]
will be dropped. See Relative Relocating for how to relocate certain columns relative to the rest.