Python 如何向 Pandas 数据框添加额外的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19365513/
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
How to add an extra row to a pandas dataframe
提问by Ahdee
If I have an empty dataframe as such:
如果我有一个空的数据框:
columns = ['Date', 'Name', 'Action','ID']
df = pd.DataFrame(columns=columns)
is there a way to append a new row to this newly created dataframe? Currently I have to create a dictionary, populate it, then append the dictionary to the dataframe at the end. Is there a more direct way?
有没有办法将新行附加到这个新创建的数据框?目前我必须创建一个字典,填充它,然后将字典附加到最后的数据帧中。有没有更直接的方法?
采纳答案by Boud
Upcoming pandas 0.13 version will allow to add rows through loc
on non existing index data. However, be aware that under the hood, this creates a copy of the entire DataFrame so it is not an efficient operation.
即将推出的 pandas 0.13 版本将允许loc
在不存在的索引数据上添加行。但是,请注意,在幕后,这会创建整个 DataFrame 的副本,因此它不是一种有效的操作。
Description is hereand this new feature is called Setting With Enlargement.
描述在这里,这个新功能叫做Setting With Enlargement。
回答by Boud
A different approach that I found ugly compared to the classic dict+append, but that works:
与经典的 dict+append 相比,我发现一种不同的方法很难看,但有效:
df = df.T
df[0] = ['1/1/2013', 'Smith','test',123]
df = df.T
df
Out[6]:
Date Name Action ID
0 1/1/2013 Smith test 123
回答by Jun
Try this:
尝试这个:
df.loc[len(df)]=['8/19/2014','Jun','Fly','98765']
Warning: this method works only if there are no "holes" in the index. For example, suppose you have a dataframe with three rows, with indices 0, 1, and 3 (for example, because you deleted row number 2). Then, len(df) = 3, so by the above command does not add a new row - it overrides row number 3.
警告:此方法仅在索引中没有“漏洞”时才有效。例如,假设您有一个包含三行的数据框,索引为 0、1 和 3(例如,因为您删除了第 2 行)。然后,len(df) = 3,因此通过上述命令不会添加新行 - 它会覆盖第 3 行。