Difference analysis of index functions loc and iloc in python pandas

  • 2021-12-04 19:03:59
  • OfStack

Directory preface 1, use row or column labels directly 2, loc function 3, iloc function summary

Preface

When using pandas for data analysis, we often need to index the rows or columns of DataFrame. There are three main ways to use pandas for indexing: using row or column labels directly, loc functions, and iloc functions.

Give a simple example:


import numpy as np
import pandas as pd
df = pd.DataFrame({"Fruits":["apple","pear","banana","watermelon"],"Price":[1.2,1.4,2.3,4.2],"Sales":[11,45,25,16]})
df

The resulting DataFrame looks like this:

Fruits Price Sales
0 apple 1.2 11
1 pear 1.4 45
2 banana 2.3 25
3 watermelon 4.2 16

1. Use row or column labels directly

If we want to select Fruits and Price columns of df, then


df[['Fruits','Price']]
Fruits Price
0 apple 1.2
1 pear 1.4
2 banana 2.3
3 watermelon 4.2

If we want to select lines 2 and 3 of df, then


df[2:4]
Fruits Price Sales
2 banana 2.3 25
3 watermelon 4.2 16

2. loc function

The loc function is indexed based on row and column labels, and its basic usage is:


DataFrame.loc[ Row label , Column label ]

If we want to select rows 2 and 3 of df and columns corresponding to Price and Sales, then


df[2:3,'Price':'Sales']
Price Sales
2 2.3 25
3 4.2 16

If we want to select all the rows and columns corresponding to Fruits and Sales, then


df.loc[:,['Fruits','Sales']]
Fruits Sales
0 apple 11
1 pear 45
2 banana 25
3 watermelon 16

3. iloc function

The iloc function is indexed based on the position of the row and column, the index value starts from 0, and the result does not include the value of the last 1 position. Its basic usage is:


DataFrame.iloc[ Row position , Column position ]

If we want to select rows 2 and 3 and columns 1 and 2 of df, then


df.iloc[2:4,1:3]
Price Sales
2 2.3 25
3 4.2 16

If we want to select all the rows and columns 0 and 2, then


df.iloc[:,[0,2]]
Fruits Sales
0 apple 11
1 pear 45
2 banana 25
3 watermelon 16

Summarize


Related articles: