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
Python: how to add a column to a pandas dataframe between two columns?
提问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 4
and 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 insert
method mutates the original DataFrame and does not return a copy.
注意:该insert
方法会改变原始 DataFrame 并且不返回副本。
If you use df = df.insert(4, 'new_col_name', tmp)
, df
will 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