我有以下DataFrame(df):
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.rand(10, 5))
我通过分配添加更多列:
df['mean'] = df.mean(1)
如何将列的意思移到前面,即将其设置为第一列,而其他列的顺序保持不变?
我有以下DataFrame(df):
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.rand(10, 5))
我通过分配添加更多列:
df['mean'] = df.mean(1)
如何将列的意思移到前面,即将其设置为第一列,而其他列的顺序保持不变?
当前回答
另一种选择是使用set_index()方法,后跟reset_index()。请注意,我们首先pop()将要移动到数据帧前面的列,以便在重置索引时避免名称冲突:
df.set_index(df.pop('column_name'), inplace=True)
df.reset_index(inplace=True)
有关详细信息,请参阅How to change the order of dataframe columns in panda。
其他回答
我认为这是一个略为简洁的解决方案:
df.insert(0, 'mean', df.pop("mean"))
这个解决方案有点类似于@JoeHeffer的解决方案,但这是一条直线。
这里,我们从数据帧中删除列“mean”,并将其附加到具有相同列名的索引0。
我相信,如果你知道另一列的位置,@Aman的答案是最好的。
如果您不知道mean的位置,但只有它的名称,则不能直接使用cols=cols[-1:]+cols[:-1]。以下是我接下来能想到的最好的东西:
meanDf = pd.DataFrame(df.pop('mean'))
# now df doesn't contain "mean" anymore. Order of join will move it to left or right:
meanDf.join(df) # has mean as first column
df.join(meanDf) # has mean as last column
假设您有列为A、B、C的df。
最简单的方法是:
df = df.reindex(['B','C','A'], axis=1)
您可以执行以下操作(从Aman的答案中借用零件):
cols = df.columns.tolist()
cols.insert(0, cols.pop(-1))
cols
>>>['mean', 0L, 1L, 2L, 3L, 4L]
df = df[cols]
与上面的答案类似,还有一种方法可以使用deque()及其rotate()方法。rotate方法获取列表中的最后一个元素并将其插入开头:
from collections import deque
columns = deque(df.columns.tolist())
columns.rotate()
df = df[columns]