Pandas DataFrame loc Example
Pandas is a powerful data manipulation library in Python. It provides data structures and functions needed to manipulate structured data. One of the most commonly used data structure in pandas is DataFrame. DataFrame is a two-dimensional labeled data structure with columns of potentially different types.
One of the most important features of pandas DataFrame is the loc attribute. It is a label-based data selection method which means that we have to pass the name of the row or column which we want to select. This method includes the last element of the range as well, unlike iloc.
In this article, we will explore various examples of using the loc attribute with pandas DataFrame.
Example 1: Selecting a Single Row by Label
Output:
Example 2: Selecting Multiple Rows by Label
Output:
Example 3: Selecting Rows with a Boolean / Conditional Lookup
Output:
Example 4: Selecting a Single Column by Label
Output:
Example 5: Selecting Multiple Columns by Label
Output:
Example 6: Selecting Rows and Columns Simultaneously
Output:
Example 7: Selecting a Range of Rows and a Range of Columns
Output:
Example 8: Selecting with a MultiIndex
Output:
Example 9: Using Slice in loc
Output:
Example 10: Using loc with a Boolean Series
Output:
In conclusion, the loc attribute provides a powerful and flexible way to access data in a pandas DataFrame. It allows us to select data by label, with a boolean array, or with a callable function. It also supports slicing and multi-indexing, making it a versatile tool for data selection and manipulation.