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

How to Rearrange Pandas DataFrame Columns?

Linda Hamilton
Release: 2024-12-12 21:00:13
Original
880 people have browsed it

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]
Copy after login

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']]
Copy after login

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'])
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template