Forum

Notifications
Clear all

[Solved] Intermediate Python (Pandas - iloc)  

   RSS

0

I would like to ask, for the following example

import pandas as pd

cars = pd.read_csv('cars.csv', index_col = 0)

print(cars.iloc[5,2])

How do you know if its going to return row 6 and row 3 from the table or its going to return row 6, column 3 from the table? The table has 7 rows and 3 columns. In the above example, it returned row 6, column 3. In such cases, is using loc better/clearer?

@zhuohx

It always will start from index 0 for both row and column. So 5,2 will always be 6,3

@zhuohx
What are you thinking of when you mean to 'print the two rows as Series'?

Topic Tags
3 Answers
0

I think I see the confusion here. iloc[5,2] is always going to return row 6 and column 3. If you want iloc to return more than one row, then the first argument to iloc has to be either a list or slice.

 

iloc[[5,2],:] will return rows 6 and 3 as a new dataframe with all columns.

0

@ilyasdeen is right!

iloc[5,2] means exactly "the row of index 5 and the column of index 2". It will never refer to two rows.

0

@zhuohx

It is always df.iloc[rows, column], so print(cars.iloc[5,2]) will print out row 6, column 3. This is a series.

If you want a dataframe, then you can do the following:

rows = [:5] # return 1st 5 rows

print(cars.iloc[rows, :]) # return 1st 5 rows, all columns. Column is explicitly specified. This is a dataframe

print(cars.iloc[rows]) # return 1st 5 rows, all columns. Column is NOT explicitly specified. This is a dataframe

Both print(cars.iloc[rows, :]) and print(cars.iloc[rows]) gives same result, but specifying the : tells you the column is explicitly specified.

Share:

Delete your account