Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to slice a Pandas Data Frame by position?

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.

like image 205
turtle Avatar asked Aug 18 '12 19:08

turtle


People also ask

How do you slice a Pandas DataFrame?

Slicing a DataFrame in Pandas includes the following steps:Ensure Python is installed (or install ActivePython) Import a dataset. Create a DataFrame. Slice the DataFrame.

How do you cut a series in Pandas?

slice() method is used to slice substrings from a string present in Pandas series object. It is very similar to Python's basic principal of slicing objects that works on [start:stop:step] which means it requires three parameters, where to start, where to end and how much elements to skip.


2 Answers

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.head.html?highlight=head#pandas.DataFrame.head

df2 = df.head(10) 

should do the trick

like image 146
RuiDC Avatar answered Sep 19 '22 16:09

RuiDC


You can also do as a convenience:

df[:10]

like image 35
Wes McKinney Avatar answered Sep 20 '22 16:09

Wes McKinney