Pandas Df Loc
[ Pandas Common Functions](#)\\\\n\\\\n* * *\\\\n\\\\n`loc[]` is a label-based indexing method in Pandas, used to select data through row labels and column labels. It is one of the most intuitive and commonly used methods in DataFrame indexing, allowing us to precisely locate the data we need.\\\\n\\\\nUnlike position-based indexing (such as `iloc[]`), `loc[]` uses the index labels set on the data itself. This means that even if the position of the data changes, as long as the labels remain the same, we can still accurately select the target data.\\\\n\\\\n* * *\\\\n\\\\n## Basic Syntax and Parameters\\\\n\\\\n`loc[]` is a DataFrame indexer, accessed through square brackets `[]`. Various forms of parameters can be passed inside the square brackets to select rows, columns, or specific cells.\\\\n\\\\n### Syntax Format\\\\n\\\\n# Select a single row (returns Series)DataFrame.loc# Select multiple rows (returns DataFrame)DataFrame.loc[[row_label1, row_label2, ...]]# Select rows and columnsDataFrame.loc[row_label, column_label]DataFrame.loc[row_slice, column_slice]DataFrame.loc[row_condition, column_condition]\\\\n### Parameter Description\\\\n\\\\n| Parameter Position | Parameter Type | Description |\\\\n| --- | --- | --- |\\\\n| First parameter (row) | Label, list of labels, label slice, boolean array | Used to select rows; can be a single label, multiple labels, a slice, or a conditional expression. |\\\\n| Second parameter (column) | Label, list of labels, label slice | Optional, used to select columns; the syntax is the same as row selection. |\\\\n\\\\n### Return Value Description\\\\n\\\\n* **Single element**: Returns a scalar value (single value).\\\\n* **Single row**: Returns a Series.\\\\n* **Multiple rows**: Returns a DataFrame.\\\\n* **Row and column combination**: Returns a Series or DataFrame depending on the selection result.\\\\n\\\\n* * *\\\\n\\\\n## Examples\\\\n\\\\nLet's fully master the usage of `loc[]` through abundant examples.\\\\n\\\\n### Example 1: Basic Usage - Using Default Index\\\\n\\\\nWhen a DataFrame uses the default integer index, the behavior of `loc[]` is similar to `iloc[]`, but it uses labels instead of positions.\\\\n\\\\n## Instance\\\\n\\\\nimport pandas as pd\\\\n\\\\n# Create Example DataFrame\\\\n\\\\n data ={\\\\n\\\\n'name': ['Alice','Bob','Charlie','David','Eve'],\\\\n\\\\n'age': [18,19,17,18,20],\\\\n\\\\n'score': [85,92,78,90,88],\\\\n\\\\n'grade': ['A','A','B','A','B']\\\\n\\\\n}\\\\n\\\\n df = pd.DataFrame(data)\\\\n\\\\nprint("Original DataFrame:")\\\\n\\\\nprint(df)\\\\n\\\\nprint()\\\\n\\\\n# Select a single row using loc (via index label)\\\\n\\\\nprint("Select row 0:")\\\\n\\\\nprint(df.loc)\\\\n\\\\nprint()\\\\n\\\\n# Select multiple rows\\\\n\\\\nprint("Select rows 1, 3, and 4:")\\\\n\\\\nprint(df.loc[[1,3,4]])\\\\n\\\\nprint()\\\\n\\\\n# Select contiguous rows using slicing'slineοΌNote: loc 'sSlicing is inclusive on both ends'sοΌ\\\\n\\\\nprint("Select rows 1 to 3 (inclusive):")\\\\n\\\\nprint(df.loc[1:3])\\\\n\\\\n**Output:**\\\\n\\\\nOriginal DataFrame: name age score grade 0 Alice 18 85 A 1 Bob 19 92 A 2 Charlie 17 78 B 3 David 18 90 A 4 Eve 20 88 B Select row 0: name Alice age 18 score 85 grade A Name: 0, dtype: objectSelect rows 1, 3, and 4: name age score grade 1 Bob 19 92 A 3 David 18 90 A 4 Eve 20 88 B Select rows 1 to 3 (inclusive): name age score grade 1 Bob 19 92 A 2 Charlie 17 78 B 3 David 18 90 A\\\\n**Code Analysis:**\\\\n\\\\n1. By default, the DataFrame's index is the integers 0, 1, 2, 3, 4.\\\\n2. `df.loc` selects the row with the index label 0, returning a Series.\\\\n3. `df.loc[[1, 3, 4]]` selects multiple rows with specific indices.\\\\n4. **Important**: The slice in `loc[]` is inclusive on both ends (unlike Python slicing), `1:3` includes indices 1, 2, and 3.\\\\n\\\\n### Example 2: Using Custom Index\\\\n\\\\nThe real power of `loc[]` lies in its ability to use custom index labels, which is the fundamental difference between it and `iloc[]`.\\\\n\\\\n## Instance\\\\n\\\\nimport pandas as pd\\\\n\\\\n# Create a DataFrame with a custom Index\\\\n\\\\n data ={\\\\n\\\\n'name': ['Alice','Bob','Charlie','David','Eve'],\\\\n\\\\n'age': [18,19,17,18,20],\\\\n\\\\n'score': [85,92,78,90,88],\\\\n\\\\n'grade': ['A','A','B','A','B']\\\\n\\\\n}\\\\n\\\\n df = pd.DataFrame(data, index=['a','b','c','d','e'])\\\\n\\\\nprint("With custom index's DataFrame:")\\\\n\\\\nprint(df)\\\\n\\\\nprint()\\\\n\\\\n# Select a single row using custom labels\\\\n\\\\nprint("Select Indexis 'b' 'sline:")\\\\n\\\\nprint(df.loc['b'])\\\\n\\\\nprint()\\\\n\\\\n# Slice using custom labels\\\\n\\\\nprint("Select Index 'b' to 'd' 'sline:")\\\\n\\\\nprint(df.loc['b':'d'])\\\\n\\\\nprint()\\\\n\\\\n# Select multiple non-contiguous rows'sIndex\\\\n\\\\nprint("Select Index 'a', 'c', 'e' 'sline:")\\\\n\\\\nprint(df.loc[['a','c','e']])\\\\n\\\\n**Output:**\\\\n\\\\nWith custom index's DataFrame: name age score grade a Alice 18 85 A b Bob 19 92 A c Charlie 17 78 B d David 18 90 A e Eve 20 88 B Select Indexis 'b' 'sline: name Bob age 19 score 92 grade A Name: b, dtype: objectSelect Index 'b' to 'd' 'sline: name age score grade b Bob 19 92 A c Charlie 17 78 B d David 18 90 A Select Index 'a', 'c', 'e' 'sline: name age score grade a Alice 18 85 A c Charlie 17 78 B e Eve 20 88 B\\\\n**Code Analysis:**\\\\n\\\\n* The custom index uses strings 'a', 'b', 'c', 'd', 'e' instead of integer indices.\\\\n* `loc[]` uses these labels to select data, which is very intuitive.\\\\n* The slice 'b':'d' includes the labels 'b', 'c', and 'd', which is also inclusive on both ends.\\\\n\\\\n### Example 3: Selecting Specific Columns\\\\n\\\\n`loc[]` can not only select rows but also select columns at the same time.\\\\n\\\\n## Instance\\\\n\\\\nimport pandas as pd\\\\n\\\\ndata ={\\\\n\\\\n'name': ['Alice','Bob','Charlie','David','Eve'],\\\\n\\\\n'age': [18,19,17,18,20],\\\\n\\\\n'score': [85,92,78,90,88],\\\\n\\\\n'grade': ['A','A','B','A','B']\\\\n\\\\n}\\\\n\\\\n df = pd.DataFrame(data, index=['a','b','c','d','e'])\\\\n\\\\n# Select specific rows'sspecific column\\\\n\\\\nprint("Select Index 'b' 's name and score column:")\\\\n\\\\nprint(df.loc['b',['name','score']])\\\\n\\\\nprint()\\\\n\\\\n# Select multiple rowsmultiplecolumn\\\\n\\\\nprint("Select Index 'a', 'c' 's name and age column:")\\\\n\\\\nprint(df.loc[['a','c'],['name','age']])\\\\n\\\\nprint()\\\\n\\\\n# Select all rows'sspecific column\\\\n\\\\nprint("All rows's name and grade column:")\\\\n\\\\nprint(df.loc[:,['name','grade']])\\\\n\\\\nprint()\\\\n\\\\n# lineCombining row slicing and column slicing\\\\n\\\\nprint("Index 'b' to 'd' 's name to score column:")\\\\n\\\\nprint(df.loc['b':'d','name':'score'])\\\\n\\\\n**Output:**\\\\n\\\\nSelect Index 'b' 's name and score column: name Bob score 92Name: b, dtype: objectSelect Index 'a', 'c' 's name and age column: name age a Alice 18 c Charlie 17All rows's name and grade column: name grade a Alice A b Bob A c Charlie B d David A e Eve B Index 'b' to 'd' 's name to score column: name age score b Bob 19 92 c Charlie 17 78 d David 18 90\\\\n**Code Analysis:**\\\\n\\\\n1. `df.loc['b', ['name', 'score']]` selects specific columns of a specific row, returning a Series.\\\\n2. `df.loc[['a', 'c'], ['name', 'age']]` selects multiple rows and multiple columns, returning a DataFrame.\\\\n3. `df.loc[:, ['name', 'grade']]` The colon indicates selecting all rows.\\\\n4. `df.loc['b':'d', 'name':'score']` Uses slices for both rows and columns simultaneously.\\\\n\\\\n### Example 4: Using Boolean Conditions for Selection\\\\n\\\\n`loc[]` supports using boolean arrays or conditional expressions to filter data, which is a very powerful feature.\\\\n\\\\n## Instance\\\\n\\\\nimport pandas as pd\\\\n\\\\ndata ={\\\\n\\\\n'name': ['Alice','Bob','Charlie','David','Eve'],\\\\n\\\\n'age': [18,19,17,18,20],\\\\n\\\\n'score': [85,92,78,90,88],\\\\n\\\\n'grade': ['A','A','B','A','B']\\\\n\\\\n}\\\\n\\\\n df = pd.DataFrame(data)\\\\n\\\\n# Select scores greater than 85 using boolean conditions 'sline\\\\n\\\\nprint("Scores greater than 85 'sstudent:")\\\\n\\\\nprint(df.loc[df['score']&
YouTip