2016-04-05 132 views
4

我想添加一列到数据标签列数据框中的两列之间的数据帧。在以下数据框中,第一列对应于索引,而第一行对应于列的名称。Python:如何将列添加到两列之间的熊猫数据框?

df 
    0 0 1 2 3 4 5 
    1 6 7 4 5 2 1 
    2 0 3 1 3 3 4 
    3 9 8 4 3 6 2 

我有tmp=[2,3,5]我想要的列45之间放,所以

df 
    0 0 1 2 3 4 5 6 
    1 6 7 4 5 2 2 1 
    2 0 3 1 3 3 3 4 
    3 9 8 4 3 6 5 2 
+1

你只需要[添加一个新的列](http://stackoverflow.com/questions/12555323/adding-new-column-to-existing-dataframe-in-python-pandas)然后[order your columns](http:// stackoverflow。 COM /问题/ 13148429 /如何对变化the- -的-数据帧列顺序)... –

回答

4

您还可以使用insert

df.insert(4, "new_col_name", tmp) 

然后改变像@Alexander explained列名。

注df.insert()没有就地参数

所以会做就地操作和返回无

df = df.insert(4, "new_col_name", tmp)将无法​​正常工作

1

首先串连你列到你的数据帧。

df2 = pd.concat([df, pd.DataFrame(tmp)], axis=1) 

然后将列重命名为所需的最终结果。

df2.columns = [0, 1, 2, 3, 4, 6, 5] 

现在对重命名的列进行排序。

df2.sort_index(axis=1, inplace=True) 

>>> df2 
    0 1 2 3 4 5 6 
0 6 7 4 5 2 2 1 
1 0 3 1 3 3 3 4 
2 9 8 4 3 6 5 2 
相关问题