Home >Backend Development >Python Tutorial >How to Rearrange Pandas DataFrame Columns?

How to Rearrange Pandas DataFrame Columns?

Linda Hamilton
Linda HamiltonOriginal
2024-12-12 21:00:13883browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn