Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I extract the nth row of a pandas data frame as a pandas data frame?

Suppose a Pandas data frame looks like:

X_test.head(4)     BoxRatio  Thrust  Velocity  OnBalRun  vwapGain 5     -0.163  -0.817     0.741     1.702     0.218 8      0.000   0.000     0.732     1.798     0.307 11     0.417  -0.298     2.036     4.107     1.793 13     0.054  -0.574     1.323     2.553     1.185 

How can I extract the third row (as row3) as a pd data frame? In other words, row3.shape should be (1,5) and row3.head() should be:

 0.417  -0.298     2.036     4.107     1.793 
like image 917
CBrauer Avatar asked Sep 19 '17 18:09

CBrauer


People also ask

How do you obtain the row numbers in a data frame?

Get Number of Rows in DataFrame You can use len(df. index) to find the number of rows in pandas DataFrame, df. index returns RangeIndex(start=0, stop=8, step=1) and use it on len() to get the count.

How do I slice a row into a DataFrame?

Slicing Rows and Columns by Index PositionWhen slicing by index position in Pandas, the start index is included in the output, but the stop index is one step beyond the row you want to select. So the slice return row 0 and row 1, but does not return row 2. The second slice [:] indicates that all columns are required.


1 Answers

Use .iloc with double brackets to extract a DataFrame, or single brackets to pull out a Series.

>>> import pandas as pd >>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]}) >>> df    col1  col2 0     1     3 1     2     4 >>> df.iloc[[1]]  # DataFrame result    col1  col2 1     2     4 >>> df.iloc[1]  # Series result col1    2 col2    4 Name: 1, dtype: int64 

This extends to other forms of DataFrame indexing as well, namely .loc and .__getitem__():

>>> df.loc[:, ['col2']]    col2 0     3 1     4  >>> df[['col2']]    col2 0     3 1     4 
like image 106
Brad Solomon Avatar answered Sep 28 '22 16:09

Brad Solomon