Pandas provide a unique method for extracting strings from a data frame.
DataFrame.loc† — it is a method that only accepts index labels and returns a string or dataframe if the index label exists in the caller’s dataframe.
Syntax: pandas.DataFrame.loc [ ]
Index label: String or list of string of index label of rows
Return type: Data frame or Series depending on parameters
To load the CSV used in the code, click here.
Example # 1: Fetching one row
In this example, the Name column is created as an index column and then two separate rows are fetched one after the other as rows using the row index label.
As shown in the output image, there were two series were returned since there was only one parameter both times.
Example # 2: multiple parameters
In this example, the Name column is created as an index column and then two separate rows are retrieved at the same time by passing a list as a parameter.
As shown in the output image, this time the return type is a data frame. Both lines were retrieved and displayed as a new data frame.
Example # 3: Retrieving multiple rows with the same index
In this example, the command name is created as an index column and one command name is passed to the .loc method to check if all values with the same name were returned commands.
As shown in the output image, all lines with the team name "Utah Jazz" were returned as a data frame.
Example # 4: extracting lines between two index marks
This example passes two row index marks and returns all rows that fall between those two index marks (both index marks are included).
As shown in the output image, all lines falling between two missing index marks , are returned in the form of a data frame.