通过整数索引选择一行 pandas 系列/数据框 [英] Selecting a row of pandas series/dataframe by integer index

查看:26
本文介绍了通过整数索引选择一行 pandas 系列/数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇为什么不支持 df[2],而 df.ix[2]df[2:3]两者都有效.

I am curious as to why df[2] is not supported, while df.ix[2] and df[2:3] both work.

In [26]: df.ix[2]
Out[26]: 
A    1.027680
B    1.514210
C   -1.466963
D   -0.162339
Name: 2000-01-03 00:00:00

In [27]: df[2:3]
Out[27]: 
                  A        B         C         D
2000-01-03  1.02768  1.51421 -1.466963 -0.162339

我希望 df[2] 以与 df[2:3] 相同的方式工作,以符合 Python 索引约定.不支持按单个整数索引行是否有设计原因?

I would expect df[2] to work the same way as df[2:3] to be consistent with Python indexing convention. Is there a design reason for not supporting indexing row by single integer?

推荐答案

回应@HYRY,请参阅 0.11 中的新文档

echoing @HYRY, see the new docs in 0.11

http://pandas.pydata.org/pandas-docs/stable/indexing.html

这里我们有新的操作符,.iloc 明确支持整数索引,.loc 明确支持标签索引

Here we have new operators, .iloc to explicity support only integer indexing, and .loc to explicity support only label indexing

例如想象一下这个场景

In [1]: df = pd.DataFrame(np.random.rand(5,2),index=range(0,10,2),columns=list('AB'))

In [2]: df
Out[2]: 
          A         B
0  1.068932 -0.794307
2 -0.470056  1.192211
4 -0.284561  0.756029
6  1.037563 -0.267820
8 -0.538478 -0.800654

In [5]: df.iloc[[2]]
Out[5]: 
          A         B
4 -0.284561  0.756029

In [6]: df.loc[[2]]
Out[6]: 
          A         B
2 -0.470056  1.192211

[] 仅对行进行切片(按标签位置)

[] slices the rows (by label location) only

这篇关于通过整数索引选择一行 pandas 系列/数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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