How to slice a Pandas Data Frame by position?

PythonPandasDataframeSlice

Python Problem Overview


I have a Pandas Data Frame object that has 1000 rows and 10 columns. I would simply like to slice the Data Frame and take the first 10 rows. How can I do this? I've been trying to use this:

>>> df.shape
(1000,10)
>>> my_slice = df.ix[10,:]
>>> my_slice.shape
(10,)

Shouldn't my_slice be the first ten rows, ie. a 10 x 10 Data Frame? How can I get the first ten rows, such that my_slice is a 10x10 Data Frame object? Thanks.

Python Solutions


Solution 1 - Python

Solution 2 - Python

You can also do as a convenience:

df[:10]

Solution 3 - Python

df.ix[10,:] gives you all the columns from the 10th row. In your case you want everything up to the 10th row which is df.ix[:9,:]. Note that the right end of the slice range is inclusive: http://pandas.sourceforge.net/gotchas.html#endpoints-are-inclusive

Solution 4 - Python

I can see at least three options:

Option 1

df[:10]

Option 2

Using head

df.head(10)

> For negative values of n, this function returns all rows except the > last n rows, equivalent to df[:-n] [Source].


Option 3

Using iloc

df.iloc[:10]

Solution 5 - Python

DataFrame[:n] will return first n rows.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionturtleView Question on Stackoverflow
Solution 1 - PythonRuiDCView Answer on Stackoverflow
Solution 2 - PythonWes McKinneyView Answer on Stackoverflow
Solution 3 - PythonDanielView Answer on Stackoverflow
Solution 4 - PythonGonçalo PeresView Answer on Stackoverflow
Solution 5 - PythonShifuView Answer on Stackoverflow