我有以下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)
如何将列的意思移到前面,即将其设置为第一列,而其他列的顺序保持不变?
当前回答
您可以使用一个集合,它是唯一元素的无序集合,以保持“其他列的顺序不变”:
other_columns = list(set(df.columns).difference(["mean"])) #[0, 1, 2, 3, 4]
然后,可以通过以下方式使用lambda将特定列移动到前面:
In [1]: import numpy as np
In [2]: import pandas as pd
In [3]: df = pd.DataFrame(np.random.rand(10, 5))
In [4]: df["mean"] = df.mean(1)
In [5]: move_col_to_front = lambda df, col: df[[col]+list(set(df.columns).difference([col]))]
In [6]: move_col_to_front(df, "mean")
Out[6]:
mean 0 1 2 3 4
0 0.697253 0.600377 0.464852 0.938360 0.945293 0.537384
1 0.609213 0.703387 0.096176 0.971407 0.955666 0.319429
2 0.561261 0.791842 0.302573 0.662365 0.728368 0.321158
3 0.518720 0.710443 0.504060 0.663423 0.208756 0.506916
4 0.616316 0.665932 0.794385 0.163000 0.664265 0.793995
5 0.519757 0.585462 0.653995 0.338893 0.714782 0.305654
6 0.532584 0.434472 0.283501 0.633156 0.317520 0.994271
7 0.640571 0.732680 0.187151 0.937983 0.921097 0.423945
8 0.562447 0.790987 0.200080 0.317812 0.641340 0.862018
9 0.563092 0.811533 0.662709 0.396048 0.596528 0.348642
In [7]: move_col_to_front(df, 2)
Out[7]:
2 0 1 3 4 mean
0 0.938360 0.600377 0.464852 0.945293 0.537384 0.697253
1 0.971407 0.703387 0.096176 0.955666 0.319429 0.609213
2 0.662365 0.791842 0.302573 0.728368 0.321158 0.561261
3 0.663423 0.710443 0.504060 0.208756 0.506916 0.518720
4 0.163000 0.665932 0.794385 0.664265 0.793995 0.616316
5 0.338893 0.585462 0.653995 0.714782 0.305654 0.519757
6 0.633156 0.434472 0.283501 0.317520 0.994271 0.532584
7 0.937983 0.732680 0.187151 0.921097 0.423945 0.640571
8 0.317812 0.790987 0.200080 0.641340 0.862018 0.562447
9 0.396048 0.811533 0.662709 0.596528 0.348642 0.563092
其他回答
只需键入要更改的列名,然后为新位置设置索引。
def change_column_order(df, col_name, index):
cols = df.columns.tolist()
cols.remove(col_name)
cols.insert(index, col_name)
return df[cols]
对于您的情况,这将是:
df = change_column_order(df, 'mean', 0)
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
下面是一个超级简单的方法示例。如果您要从excel复制标题,请使用.split('\t')
df = df['FILE_NAME DISPLAY_PATH SHAREPOINT_PATH RETAILER LAST_UPDATE'.split()]
我有一个在panda中重新排序列名的非常具体的用例。有时我在基于现有列的数据帧中创建一个新列。默认情况下,panda将在末尾插入我的新列,但我希望新列插入到它派生的现有列旁边。
def rearrange_list(input_list, input_item_to_move, input_item_insert_here):
'''
Helper function to re-arrange the order of items in a list.
Useful for moving column in pandas dataframe.
Inputs:
input_list - list
input_item_to_move - item in list to move
input_item_insert_here - item in list, insert before
returns:
output_list
'''
# make copy for output, make sure it's a list
output_list = list(input_list)
# index of item to move
idx_move = output_list.index(input_item_to_move)
# pop off the item to move
itm_move = output_list.pop(idx_move)
# index of item to insert here
idx_insert = output_list.index(input_item_insert_here)
# insert item to move into here
output_list.insert(idx_insert, itm_move)
return output_list
import pandas as pd
# step 1: create sample dataframe
df = pd.DataFrame({
'motorcycle': ['motorcycle1', 'motorcycle2', 'motorcycle3'],
'initial_odometer': [101, 500, 322],
'final_odometer': [201, 515, 463],
'other_col_1': ['blah', 'blah', 'blah'],
'other_col_2': ['blah', 'blah', 'blah']
})
print('Step 1: create sample dataframe')
display(df)
print()
# step 2: add new column that is difference between final and initial
df['change_odometer'] = df['final_odometer']-df['initial_odometer']
print('Step 2: add new column')
display(df)
print()
# step 3: rearrange columns
ls_cols = df.columns
ls_cols = rearrange_list(ls_cols, 'change_odometer', 'final_odometer')
df=df[ls_cols]
print('Step 3: rearrange columns')
display(df)
您可以使用以下名称列表对数据帧列进行重新排序:
df=df.filter(list_of_col_name)