Absolutely! Let’s break it down clearly with a comparison between .loc and .iloc, and then explain why they are often used when filling empty rows in a DataFrame.
1. .loc vs .iloc in Pandas
|
Feature |
.loc |
.iloc |
|---|---|---|
|
Selection type |
Label-based (row/column names) |
Integer position-based (row/column indices) |
|
Includes the endpoint in slices? |
Yes |
No |
|
Accepts boolean masks? |
Yes |
Yes |
|
Examples |
df.loc[0, 'Age'] → value in row label 0, column ‘Age’df.loc[:, ['Name','City']] → select columns by names |
df.iloc[0, 1] → value in row 0, column 1df.iloc[:, 0:2] → select first 2 columns by position |
|
When used |
When you know labels |
When you know positions |
2. Why they are used in filling empty rows (NaN)
When a DataFrame has missing values (NaN), you often want to fill them with specific values, either for a whole column or a specific row. Both .loc and .iloc are helpful:
-
.loc → Use it if you want to fill based on row or column labels.
-
.iloc → Use it if you want to fill based on row or column positions.
Example 1: Using .loc
import pandas as pd
import numpy as np
df = pd.DataFrame({
'Name': ['Alice', 'Bob', None],
'Age': [25, np.nan, 35]
})
# Fill missing name for row label 2
df.loc[2, 'Name'] = 'Charlie'
# Fill missing Age for all rows where Age is NaN
df.loc[df['Age'].isna(), 'Age'] = 30
print(df)
Output:
Name Age
0 Alice 25.0
1 Bob 30.0
2 Charlie 35.0
Example 2: Using .iloc
# Fill the missing Age using row/column position
df.iloc[1, 1] = 30 # Row 1, Column 1 → Age
-
Handy when labels are unknown or you just want quick positional indexing.
-
Especially useful in loops, numeric operations, or filling missing values systematically.
✅ Summary:
-
Use .loc for clarity and readability when you know labels.
-
Use .iloc when working with positions, often in automated or iterative filling of missing data.
-
Both allow direct assignment of missing values, making them essential tools for data cleaning.
0 Comments