pandas Python:如何在两列之间的熊猫数据框中添加一列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36437849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:00:14  来源:igfitidea点击:

Python: how to add a column to a pandas dataframe between two columns?

pythonpandasdataframe

提问by emax

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 

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

我有tmp=[2,3,5]我想放在列4和之间5,所以

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 

回答by ayhan

You can use insert:

您可以使用insert

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

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

注意:该insert方法会改变原始 DataFrame 并且不返回副本。

If you use df = df.insert(4, 'new_col_name', tmp), dfwill be None.

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

回答by Alexander

First concatenate your column to your dataframe.

首先将您的列连接到您的数据框。

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

Then rename the columns to the desired end result.

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

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

Now sort on the renamed columns.

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

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