更改DataFrame最后一行中的元素 [英] Change an element in the last row of a DataFrame

查看:261
本文介绍了更改DataFrame最后一行中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I set up a simple DataFrame in pandas:

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

我希望能够更改其最后一行中的单个元素.在pandas == 0.13.1中,我可以使用以下代码:

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:

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

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

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

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

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

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.

如何在较新版本的Pandas中执行此操作?我意识到我可以像这样使用最后一行的索引:

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

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?

推荐答案

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

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

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

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

这篇关于更改DataFrame最后一行中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆