Home >Backend Development >Python Tutorial >How to Rearrange Pandas DataFrame Columns?
How to Rearrange DataFrame Column Order
Changing the order of DataFrame columns may be necessary to group or present data in a specific way. Here's how to achieve this using pandas:
Using List Assignment:
One straightforward approach is to reassign the columns in the desired order. To move a column to the front, simply move its name to the beginning of a list that contains the column names. For example:
df = pd.DataFrame(np.random.rand(10, 5)) df['mean'] = df.mean(1) # Rearrange columns cols = df.columns.tolist() cols = ['mean'] + cols[1:] df = df[cols]
Using loc:
Alternatively, loc can be used to selectively assign rows and columns. To move a column to the beginning, use : for the rows and the desired column name as the first argument to loc. For example:
df = pd.DataFrame(np.random.rand(10, 5)) df['mean'] = df.mean(1) # Rearrange columns df = df.loc[:, ['mean']]
Using insert:
The insert method allows inserting a column at a specific position. To move a column to the front, use 0 as the position argument. For example:
df = pd.DataFrame(np.random.rand(10, 5)) df['mean'] = df.mean(1) # Rearrange columns df.insert(0, 'mean', df['mean'])
The above is the detailed content of How to Rearrange Pandas DataFrame Columns?. For more information, please follow other related articles on the PHP Chinese website!