我在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
Run Code Online (Sandbox Code Playgroud)
我希望能够改变最后一行中的单个元素.在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
Run Code Online (Sandbox Code Playgroud)
但在更新到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
Run Code Online (Sandbox Code Playgroud)
问题当然是-1不是索引a
,所以我不能使用loc
.正如警告所示,我没有更改'a'
最后一行的列,我只更改了丢弃的本地副本.
如何在较新版本的熊猫中执行此操作?我意识到我可以使用最后一行的索引,如:
a.loc[2,'a'] = 77
Run Code Online (Sandbox Code Playgroud)
但我将使用多行具有相同索引的表,并且我不想每次都重新索引我的表.有没有办法在不知道前一行的最后一行索引的情况下做到这一点?
小智 22
从@PallavBakshi 和@Mike 的解决方案中获取元素,以下在 Pandas >= 0.19 中有效
仅使用 iloc[-1, 'a] 将不起作用,因为 -1 不在索引中。
a.loc[a.index[-1], 'a']= 4.0
Run Code Online (Sandbox Code Playgroud)
Mik*_*ike 10
好吧,我找到了一种解决这个问题的方法,无需链接,也不用担心多个索引.
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
Run Code Online (Sandbox Code Playgroud)
我iloc
之前无法使用,因为我无法将列索引作为int提供,但get_loc
解决了这个问题.感谢大家的有益评论!
归档时间: |
|
查看次数: |
12322 次 |
最近记录: |