我有以下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)
如何将列的意思移到前面,即将其设置为第一列,而其他列的顺序保持不变?
当前回答
你也可以这样做:
df = df[['mean', '0', '1', '2', '3']]
您可以通过以下方式获取列列表:
cols = list(df.columns.values)
输出将产生:
['0', '1', '2', '3', 'mean']
…然后,在将其放入第一个函数之前,可以手动重新排列
其他回答
使用T怎么样?
df = df.T.reindex(['mean', 0, 1, 2, 3, 4]).T
这里有一个函数可以对任意数量的列执行此操作。
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
我想到了和Dmitriy Work一样的答案,显然是最简单的:
df["mean"] = df.mean(1)
l = list(np.arange(0,len(df.columns) -1 ))
l.insert(0,-1)
df.iloc[:,l]
我认为这个函数更简单。您只需在开始或结束处或同时指定列的子集:
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]
您可以使用以下名称列表对数据帧列进行重新排序:
df=df.filter(list_of_col_name)