Python:如何在两列之间的 pandas 数据框中添加一列? [英] Python: how to add a column to a pandas dataframe between two columns?

查看:538
本文介绍了Python:如何在两列之间的 pandas 数据框中添加一列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一列添加到两列之间的数据框中,其编号为column dataframe.在以下数据框中,第一列对应于索引,而第一行对应于列的名称.

I would like to add a column to a dataframe between two columns in number labeled columns dataframe. In the following dataframe the first column corresponds to the index while the first row to the name of the columns.

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之间,所以

I have tmp=[2,3,5] that I want to put between the columns 4 and 5, so

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 

推荐答案

您可以使用

You can use insert:

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

注意:insert方法会变异原始DataFrame,并且不返回副本.

Note: The insert method mutates the original DataFrame and does not return a copy.

如果使用df = df.insert(4, 'new_col_name', tmp),则df将是None.

这篇关于Python:如何在两列之间的 pandas 数据框中添加一列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆