我有以下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)
如何将列的意思移到前面,即将其设置为第一列,而其他列的顺序保持不变?
当前回答
我认为这个函数更简单。您只需在开始或结束处或同时指定列的子集:
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]
其他回答
这里有一个函数可以对任意数量的列执行此操作。
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
只需按所需顺序分配列名:
In [39]: df
Out[39]:
0 1 2 3 4 mean
0 0.172742 0.915661 0.043387 0.712833 0.190717 1
1 0.128186 0.424771 0.590779 0.771080 0.617472 1
2 0.125709 0.085894 0.989798 0.829491 0.155563 1
3 0.742578 0.104061 0.299708 0.616751 0.951802 1
4 0.721118 0.528156 0.421360 0.105886 0.322311 1
5 0.900878 0.082047 0.224656 0.195162 0.736652 1
6 0.897832 0.558108 0.318016 0.586563 0.507564 1
7 0.027178 0.375183 0.930248 0.921786 0.337060 1
8 0.763028 0.182905 0.931756 0.110675 0.423398 1
9 0.848996 0.310562 0.140873 0.304561 0.417808 1
In [40]: df = df[['mean', 4,3,2,1]]
现在,“mean”列出现在前面:
In [41]: df
Out[41]:
mean 4 3 2 1
0 1 0.190717 0.712833 0.043387 0.915661
1 1 0.617472 0.771080 0.590779 0.424771
2 1 0.155563 0.829491 0.989798 0.085894
3 1 0.951802 0.616751 0.299708 0.104061
4 1 0.322311 0.105886 0.421360 0.528156
5 1 0.736652 0.195162 0.224656 0.082047
6 1 0.507564 0.586563 0.318016 0.558108
7 1 0.337060 0.921786 0.930248 0.375183
8 1 0.423398 0.110675 0.931756 0.182905
9 1 0.417808 0.304561 0.140873 0.310562
我相信,如果你知道另一列的位置,@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
import numpy as np
import pandas as pd
df = pd.DataFrame()
column_names = ['x','y','z','mean']
for col in column_names:
df[col] = np.random.randint(0,100, size=10000)
您可以尝试以下解决方案:
解决方案1:
df = df[ ['mean'] + [ col for col in df.columns if col != 'mean' ] ]
解决方案2:
df = df[['mean', 'x', 'y', 'z']]
解决方案3:
col = df.pop("mean")
df = df.insert(0, col.name, col)
解决方案4:
df.set_index(df.columns[-1], inplace=True)
df.reset_index(inplace=True)
解决方案5:
cols = list(df)
cols = [cols[-1]] + cols[:-1]
df = df[cols]
解决方案6:
order = [1,2,3,0] # setting column's order
df = df[[df.columns[i] for i in order]]
时间比较:
解决方案1:
CPU时间:用户1.05 ms,sys:35µs,总计:1.08 ms壁时间:995µs
解决方案2:
CPU时间:用户933µs,系统:0 ns,总计:933µ壁时间:800µs
解决方案3:
CPU时间:用户0 ns,sys:1.35 ms,总计:1.35 ms壁时间:1.08 ms
解决方案4:
CPU时间:用户1.23毫秒,系统:45µs,总计:1.27毫秒壁时间:986µs
解决方案5:
CPU时间:用户1.09 ms,系统:19µs,总计:1.11 ms壁时间:949µs
解决方案6:
CPU时间:用户955µs,系统:34µs,总计:989µs壁时间:859µs
使用T怎么样?
df = df.T.reindex(['mean', 0, 1, 2, 3, 4]).T