如何更改DataFrame列的顺序? [英] How to change the order of DataFrame columns?

查看:671
本文介绍了如何更改DataFrame列的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下DataFrame(df):

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.rand(10, 5))

我通过分配添加了更多列:

I add more column(s) by assignment:

df['mean'] = df.mean(1)

如何将列mean移到最前面,即将其设置为第一列,而其他列的顺序保持不变?

How can I move the column mean to the front, i.e. set it as first column leaving the order of the other columns untouched?

推荐答案

您还可以执行以下操作:

You could also do something like this:

df = df[['mean', '0', '1', '2', '3']]

您可以通过以下方式获取列列表:

You can get the list of columns with:

cols = list(df.columns.values)

输出将产生:

['0', '1', '2', '3', 'mean']

...然后在将其放入第一个功能之前很容易手动重新排列

...which is then easy to rearrange manually before dropping it into the first function

这篇关于如何更改DataFrame列的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆