Selection on DataFrame with iloc [ ]:

  • You can select rows based on their integer position with the .iloc[ ] attribute.
  • For example, imagine we want to determine the top 5 tip amounts in the tips.csv dataset.
python
1import pandas as pd
2
3df = pd.read_csv('./Data/tips.csv')
4
5df = df.sort_values(by='tip', ascending=False)
6df = df.iloc[:5]
7print(df)
8print(df.shape)
  • On line 6, iloc[:5] is used to select the first 5 rows of the DataFrame after it has been sorted.

Output:

1     total_bill    tip   sex smoker   day    time  size
2170       50.81  10.00  Male    Yes   Sat  Dinner     3
3212       48.33   9.00  Male     No   Sat  Dinner     4
423        39.42   7.58  Male     No   Sat  Dinner     4
559        48.27   6.73  Male     No   Sat  Dinner     4
6141       34.30   6.70  Male     No  Thur   Lunch     6
7(5, 7)

Retrieve the Last 5 Rows:

  • To retrieve the last 5 rows of a DataFrame, we can pass in -5:, .iloc[-5:].
  • This will alternatively identify the lowest 5 tip amounts in the dataset.
python
1import pandas as pd
2
3df = pd.read_csv('./Data/tips.csv')
4
5df = df.sort_values(by='tip', ascending=False)
6df = df.iloc[-5:]
7print(df)
8print(df.shape)

Output:

1     total_bill   tip     sex smoker  day    time  size
20         16.99  1.01  Female     No  Sun  Dinner     2
3236       12.60  1.00    Male    Yes  Sat  Dinner     2
4111        7.25  1.00  Female     No  Sat  Dinner     1
567         3.07  1.00  Female    Yes  Sat  Dinner     1
692         5.75  1.00  Female    Yes  Fri  Dinner     2
7(5, 7)

Retrieve the First, Third and Fifth rows:

python
1import pandas as pd
2
3df = pd.read_csv('./Data/tips.csv')
4
5df = df.iloc[[0, 3, 5]]
6print(df)
7print(df.shape)

Output:

1   total_bill   tip     sex smoker  day    time  size
20       16.99  1.01  Female     No  Sun  Dinner     2
33       23.68  3.31    Male     No  Sun  Dinner     2
45       25.29  4.71    Male     No  Sun  Dinner     4
5(3, 7)
  • On line 5, iloc[[0, 3, 5]] has two square brackets, which is used to pass in a list of indices to select.