我有以下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。
其他回答
我想在一个数据帧前面加上两列,我不知道所有列的确切名称,因为它们是从之前的pivot语句生成的。所以,如果你也遇到同样的情况:把你知道名字的列放在前面,然后让它们跟着“所有其他列”,我提出了以下一般解决方案:
df = df.reindex_axis(['Col1','Col2'] + list(df.columns.drop(['Col1','Col2'])), axis=1)
这里有一种移动一个现有列的方法,它将修改现有的数据帧。
my_column = df.pop('column name')
df.insert(3, my_column.name, my_column) # Is in-place
此函数避免了您只需列出数据集中的每个变量来对其中的几个变量进行排序。
def order(frame,var):
if type(var) is str:
var = [var] #let the command take a string or list
varlist =[w for w in frame.columns if w not in var]
frame = frame[var+varlist]
return frame
它需要两个参数,第一个是数据集,第二个是要放到前面的数据集中的列。
所以在我的例子中,我有一个名为Frame的数据集,其中包含变量A1、A2、B1、B2、Total和Date。如果我想把道达尔带到前面,那么我所要做的就是:
frame = order(frame,['Total'])
如果我想将Total和Date带到前台,那么我会:
frame = order(frame,['Total','Date'])
编辑:
另一种有用的使用方法是,如果您有一个不熟悉的表,并且正在查找其中包含特定术语的变量,例如VAR1、VAR2,。。。您可以执行以下操作:
frame = order(frame,[v for v in frame.columns if "VAR" in v])
DataFrame.sort_index(axis=1)非常干净。请在此处检查文档。然后凹入
我认为这个函数更简单。您只需在开始或结束处或同时指定列的子集:
def reorder_df_columns(df, start=None, end=None):
"""
This function reorder columns of a DataFrame.
It takes columns given in the list `start` and move them to the left.
Its also takes columns in `end` and move them to the right.
"""
if start is None:
start = []
if end is None:
end = []
assert isinstance(start, list) and isinstance(end, list)
cols = list(df.columns)
for c in start:
if c not in cols:
start.remove(c)
for c in end:
if c not in cols or c in start:
end.remove(c)
for c in start + end:
cols.remove(c)
cols = start + cols + end
return df[cols]