向 Pandas 数据框插入一列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45844751/
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 04:18:13  来源:igfitidea点击:

Insert a column to a pandas dataframe

pythonpandasdataframe

提问by DGMS89

Scenario:I have a code that reads data from excel worksheets into dataframes, merges into one dataframe, and perform some cleaning procedures.

场景:我有一个代码可以将 Excel 工作表中的数据读取到数据帧中,合并到一个数据帧中,并执行一些清理程序。

Issue:I am trying to add a column with a given value to the beginning of the dataframe with pd.insert, but every time I run this line the dataframe disappears from the variable explorer.

问题:我正在尝试使用 pd.insert 将具有给定值的列添加到数据框的开头,但每次运行此行时,数据框都会从变量资源管理器中消失。

This is the line I am using:

这是我正在使用的线路:

fnl = fnl.insert(loc=1, column='N', value=15)

Question:Why could be the reason for this, and how to fix it?

问题:为什么会出现这种情况,如何解决?

回答by piRSquared

pd.DataFrame.insertacts in place and doesn't return anything. All you need is

pd.DataFrame.insert行动到位,不返回任何东西。所有你需要的是

fnl.insert(1, 'N', 15)

Because it returns nothing, you were assigning Noneto fnland that's why it was disappearing.

因为它什么都不返回,所以你正在分配None给它fnl,这就是它消失的原因。

回答by Alexander

You could also append it to the end of the dataframe (the order of the columns generally shouldn't matter except for presentation purposes).

您还可以将其附加到数据框的末尾(列的顺序通常应该无关紧要,除非出于演示目的)。

fnl = fnl.assign(N=15)

This returns a copy of the dataframe with the new column Nadded with values equal to 15.

这将返回数据框的副本,其中N添加了值等于 15的新列。

Because the index doesn't matter in this case, it should be more efficient to append via:

因为在这种情况下索引无关紧要,所以通过以下方式附加应该更有效:

fnl['N'] = 15