pandas 更改 DataFrame 最后一行中的元素

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

Change an element in the last row of a DataFrame

pythonpandas

提问by Mike

I set up a simple DataFrame in pandas:

我在 Pandas 中设置了一个简单的 DataFrame:

a = pandas.DataFrame([[1,2,3], [4,5,6], [7,8,9]], columns=['a','b','c'])
>>> print a
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

I would like to be able to alter a single element in the last row of. In pandas==0.13.1 I could use the following:

我希望能够更改最后一行中的单个元素。在 pandas==0.13.1 我可以使用以下内容:

a.iloc[-1]['a'] = 77
>>> print a
    a  b  c
0   1  2  3
1   4  5  6
2  77  8  9

but after updating to pandas==0.14.1, I get the following warning when doing this:

但是在更新到 pandas==0.14.1 后,我在执行此操作时收到以下警告:

SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead

The problem of course being that -1 is not an index of a, so I can't use loc. As the warning indicates, I have not changed column 'a'of the last row, I've only altered a discarded local copy.

问题当然是 -1 不是 的索引a,所以我不能使用loc. 正如警告所示,我没有更改'a'最后一行的列,我只更改了丢弃的本地副本。

How do I do this in the newer version of pandas? I realize I could use the index of the last row like:

我如何在较新版本的Pandas中做到这一点?我意识到我可以使用最后一行的索引,例如:

a.loc[2,'a'] = 77

But I'll be working with tables where multiple rows have the same index, and I don't want to reindex my table every time. Is there a way to do this without knowing the index of the last row before hand?

但是我将使用多行具有相同索引的表,并且我不想每次都重新索引我的表。有没有办法在不事先知道最后一行的索引的情况下做到这一点?

采纳答案by Mike

Alright I've found a way to solve this problem without chaining, and without worrying about multiple indices.

好吧,我找到了一种无需链接即可解决此问题的方法,无需担心多个索引。

a.iloc[-1, a.columns.get_loc('a')] = 77
>>> a
   a  b  c
0  1  2  3
1  4  5  6
2 77  8  9

I wasn't able to use ilocbefore because I couldn't supply the column index as an int, but get_locsolves that problem. Thanks for the helpful comments everyone!

iloc之前无法使用,因为我无法将列索引作为 int 提供,但get_loc解决了该问题。感谢大家的有益评论!

回答by brunostuyts

Taking elements from the solutions of @PallavBakshi and @Mike, the following works in Pandas >= 0.19

从@PallavBakshi 和@Mike 的解决方案中获取元素,以下在 Pandas >= 0.19 中有效

Just using iloc[-1, 'a] won't work as -1 is not in the index.

仅使用 iloc[-1, 'a] 将不起作用,因为 -1 不在索引中。

a.loc[a.index[-1], 'a']= 4.0

回答by PallavBakshi

For pandas 0.22,

对于Pandas 0.22,

a.at[a.index[-1], 'a'] = 77

this is just one of the ways.

这只是其中一种方式。