MLE
MLE

Reputation: 1043

possible index by column number (not label) without iloc?

Can we index both the row and column in pandas without using.iloc? The documentations says

With DataFrame, slicing inside of [] slices the rows.

But when I want to include both row and column in the same fashion, it is not working.

   data = pandas.DataFrame(np.random.rand(10,5), columns = list('abcde'))
   data[0:2] #only rows
   data.iloc[0:2,0:3] # works.
   data[0:2,0:3] # not working in python, but it works similarly in R

Upvotes: 0

Views: 869

Answers (1)

zachd1_618
zachd1_618

Reputation: 4340

I agree that using iloc is probably the clearest solution, but indexing by row and column number simultaneously can be done with two separate indexing operations. Unless you use iloc, I don't think pandas knows if you are looking for columns number 0-3, or columns named 0, 1, 2, and 3

data[0:2][data.columns[0:3]]

This is fairly clear though in showing exactly what you are selecting. Otherwise, you'll have to drop into array indexing to get your subset.

data.values[0:2,0:3] 

Upvotes: 2

Related Questions