Suppose a Pandas dataframe looks like:
JavaScript
x
6
1
BoxRatio Thrust Velocity OnBalRun vwapGain
2
5 -0.163 -0.817 0.741 1.702 0.218
3
8 0.000 0.000 0.732 1.798 0.307
4
11 0.417 -0.298 2.036 4.107 1.793
5
13 0.054 -0.574 1.323 2.553 1.185
6
How can I extract the third row (as row3) as a pandas dataframe?
In other words, row3.shape
should be (1,5) and row3.head()
should be:
JavaScript
1
2
1
0.417 -0.298 2.036 4.107 1.793
2
Advertisement
Answer
Use .iloc
with double brackets to extract a DataFrame, or single brackets to pull out a Series.
JavaScript
1
14
14
1
>>> import pandas as pd
2
>>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
3
>>> df
4
col1 col2
5
0 1 3
6
1 2 4
7
>>> df.iloc[[1]] # DataFrame result
8
col1 col2
9
1 2 4
10
>>> df.iloc[1] # Series result
11
col1 2
12
col2 4
13
Name: 1, dtype: int64
14
This extends to other forms of DataFrame indexing as well, namely .loc
and .__getitem__()
:
JavaScript
1
10
10
1
>>> df.loc[:, ['col2']]
2
col2
3
0 3
4
1 4
5
6
>>> df[['col2']]
7
col2
8
0 3
9
1 4
10