我有以下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)
如何将列的意思移到前面,即将其设置为第一列,而其他列的顺序保持不变?
当前回答
我相信,如果你知道另一列的位置,@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
其他回答
DataFrame.sort_index(axis=1)非常干净。请在此处检查文档。然后凹入
简单地说,
df = df[['mean'] + df.columns[:-1].tolist()]
这里有一个函数可以对任意数量的列执行此操作。
def mean_first(df):
ncols = df.shape[1] # Get the number of columns
index = list(range(ncols)) # Create an index to reorder the columns
index.insert(0,ncols) # This puts the last column at the front
return(df.assign(mean=df.mean(1)).iloc[:,index]) # new df with last column (mean) first
您需要按所需的顺序创建一个新的列列表,然后使用df=df[cols]以新的顺序重新排列列。
cols = ['mean'] + [col for col in df if col != 'mean']
df = df[cols]
您也可以使用更通用的方法。在本例中,最后一列(由-1表示)作为第一列插入。
cols = [df.columns[-1]] + [col for col in df if col != df.columns[-1]]
df = df[cols]
如果DataFrame中存在列,也可以使用此方法按所需顺序重新排序列。
inserted_cols = ['a', 'b', 'c']
cols = ([col for col in inserted_cols if col in df]
+ [col for col in df if col not in inserted_cols])
df = df[cols]
在您的情况下,
df = df.reindex(columns=['mean',0,1,2,3,4])
会做你想做的事。
在我的情况下(一般形式):
df = df.reindex(columns=sorted(df.columns))
df = df.reindex(columns=(['opened'] + list([a for a in df.columns if a != 'opened']) ))