Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

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

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?

1 Answer

0 votes
by (106k points)

For selecting a row of pandas series/dataframe by integer index we have new operators which are .iloc, it explicitly supports only integer indexing, and .loc explicitly support only label indexing.

An example that shows the use of both the operators:-

import pandas as pd

import numpy as np

df =pd.DataFrame(np.random.rand(5,2),index=range(0,10,2)

,columns=list('AB')) 

print(df) 

print(df.iloc[[2]])

print(df.loc[[2]])

image

Related questions

Browse Categories

...