如何在pandas的特定列索引处插入列?

我可以在pandas的特定列索引处插入一列吗?

import pandas as pd df = pd.DataFrame({'l':['a','b','c','d'], 'v':[1,2,1,2]}) df['n'] = 0 

这将把列n作为df的最后一列,但没有办法告诉dfn放在开头?

请参阅文档: http : //pandas.pydata.org/pandas-docs/stable/dsintro.html#column-selection-addition-deletion

使用idx = 0会在开头插入

 df.insert(idx, col_name, value) 

 df = pd.DataFrame({'B': [1, 2, 3], 'C': [4, 5, 6]}) df Out: BC 0 1 4 1 2 5 2 3 6 idx = 0 new_col = [7, 8, 9] # can be a list, a Series, an array or a scalar df.insert(loc=idx, column='A', value=new_col) df Out: ABC 0 7 1 4 1 8 2 5 2 9 3 6 

你可以尝试提取列作为列表,按下这个你想要的,并重新索引你的数据框:

 >>> cols = df.columns.tolist() >>> cols = [cols[-1]]+cols[:-1] # or whatever change you need >>> df.reindex(columns=cols) nlv 0 0 a 1 1 0 b 2 2 0 c 1 3 0 d 2 

编辑:这可以在一行完成。 不过,这看起来有点难看。 也许有些清洁scheme可能会来…

 >>> df.reindex(columns=['n']+df.columns[:-1].tolist()) nlv 0 0 a 1 1 0 b 2 2 0 c 1 3 0 d 2