[Solved] Intermediate Python (Pandas - iloc)
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?
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'?
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.
@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.
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.
Latest Post: Why KELABERTIV? Our newest member: joeiwsm Recent Posts Unread Posts Tags
Forum Icons: Forum contains no unread posts Forum contains unread posts
Topic Icons: Not Replied Replied Active Hot Sticky Unapproved Solved Private Closed