Difference Between .iloc and .loc in Pandas
Even though we can access the pandas data frame by the normal way (dataframe<column_name>.[index], we have another two ways to access the data frame.
- iloc
- loc
We shall create a sample data frame by which can understand better about this above-mentioned operations
Above code creates a data frame with columns a and b as shown in the figure below
a | b | |
---|---|---|
0 | 1 | 6 |
1 | 2 | 7 |
2 | 3 | 8 |
3 | 4 | 9 |
4 | 5 | 10 |
**Now let's try to print rows of the data frame using iloc and loc functions**
data.iloc[0]
a 1
b 6
Name: 0, dtype: int64
data.loc[0]
a 1
b 6
Name: 0, dtype: int64
data.iloc[0] and data.loc[0] both are giving same result? of course yes, in this case, let’s try to shuffle the data and then try to print the rows using iloc and loc functions. To shuffle the data we have the random operation in the numpy library.
import numpy as np
x = np.random.permutation(data.shape[0])
x
array([1, 4, 0, 2, 3])
np.random.permutation(num) gives us the shuffled values up to num, here, in this case, num is the number of rows in the data frame As we got x as shuffled index values we shall create a new data frame with these index numbers.
**Now new data frame is created with shuffled index values**
data = data.iloc[x]
data
a | b | |
---|---|---|
4 | 5 | 10 |
3 | 4 | 9 |
1 | 2 | 7 |
0 | 1 | 6 |
2 | 3 | 8 |
Let’s try to print row using loc and iloc functions
data.loc[1] — This gives the row at element 1 i.e 2 and 4 data.iloc[1] — This gives the row at index element 1 i.e 5 & 10
See below figure for clarification
data.iloc[1]
a 4
b 9
Name: 3, dtype: int64
data.loc[1]
a 2
b 7
Name: 1, dtype: int64
As we see in image iloc is the operation of locating the index And loc is the operation of locating the element
Tip :
:bulb:
To remember iloc and loc, even after shuffling the data to access with index number use loc, to access the elements through indexing after shuffling, use iloc.
If there is any typo or mistakes in this article/blog, please let me know by commenting below. Thank You For Reading
Load Comments