In this blog we will look at how we can leverage iloc to access specific rows in a data frame¶
Step 1: Import the libraries¶
In [1]:
import pandas as pd
import numpy as np
Step 2:Creating the Data Frame¶
In [10]:
Day=['Day '+ str(i+1) for i in range(10)]
Day
Out[10]:
['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5', 'Day 6', 'Day 7', 'Day 8', 'Day 9', 'Day 10']
In [14]:
df = pd.DataFrame(Day)
df['Random_Values']=np.random.rand(10)
df.columns=['Day','Random_Values']
df
Out[14]:
Day | Random_Values | |
---|---|---|
0 | Day 1 | 0.780147 |
1 | Day 2 | 0.726025 |
2 | Day 3 | 0.960263 |
3 | Day 4 | 0.445348 |
4 | Day 5 | 0.148012 |
5 | Day 6 | 0.219381 |
6 | Day 7 | 0.287973 |
7 | Day 8 | 0.403218 |
8 | Day 9 | 0.607353 |
9 | Day 10 | 0.415898 |
Step 3:Using iloc to access rows between 3 and 5¶
In [15]:
df.iloc[3:6]
Out[15]:
Day | Random_Values | |
---|---|---|
3 | Day 4 | 0.445348 |
4 | Day 5 | 0.148012 |
5 | Day 6 | 0.219381 |
Step 4: Accessing specific column while using iloc¶
In [16]:
df.iloc[3:6]['Day']
Out[16]:
3 Day 4 4 Day 5 5 Day 6 Name: Day, dtype: object