pandas.DataFrame.loc Property allows us to select a row by its column value. Here, the key point is we can also select multiple rows with the help of the loc property. While selecting multiple rows we need to define the number of rows along with column names (in case we don't need all the columns).
Let us understand with the help of some examples.
Syntax:
DataFrame.loc[x:y,['col-name1',col-name2]]
Here, x and y are starting and ending indexes respectively. x represents the first row whereas y represents the last row.
To work with Python Pandas, we need to import the pandas library. Below is the syntax,
import pandas as pd
Example 1: Selecting two rows and two columns
Output:
Explanation:
Since we have changed the index names to subject names while creating the DataFrame, we need to pass the list of rows up to which we want to view our data.
Example 2: Selecting all the rows and just one column
Output:
Explanation:
Here, we need to pass a list of all the index names to select all the rows. If we want all the column names to be printed so we do not need to define a specific list of column names.
Note: In case we have a large data set, we do not assign specific index names and hence in this case multiple rows can be selected by passing sliced index in loc[] property.
Example 3:
Output:
Explanation:
We know that the index ranges from 0 to n-1, where n is the number of rows. In the above example, we will pass a sliced index (1:3) instead of list of index names to select two rows (2nd row and 3rd row) and we will pass a list of specific column names that we want to display.