Pandas DataFrame ‘loc’ Keyword.
Table Of Contents:
- Syntax For ‘loc’ Keyword In Data Frame.
- Examples Of ‘loc’ Keyword.
(1) Syntax:
pandas.DataFrame.loc
Description:
Access a group of rows and columns by label(s) or a boolean array.
.loc[]
is primarily label based, but may also be used with a boolean array.
Allowed inputs are:
A single label, e.g.
5
or'a'
, (note that5
is interpreted as a label of the index, and never as an integer position along the index).A list or array of labels, e.g.
['a', 'b', 'c']
.A slice object with labels, e.g.
'a':'f'
.A boolean array of the same length as the axis being sliced, e.g.
[True, False, True]
.An alignable boolean Series. The index of the key will be aligned before masking.
An alignable Index. The Index of the returned selection will be the input.
A
callable
function with one argument (the calling Series or DataFrame) and that returns valid output for indexing (one of the above)
Raises
KeyError
If any items are not found.
- IndexingError
If an indexed key is passed and its index is unalignable to the frame index.
(2) Examples Of ‘loc’ Keyword:
Example-1
import pandas as pd
student = {'Name':['Subrat','Abhispa','Arpita','Anuradha','Namita'],
'Roll_No':[100,101,102,103,104],
'Subject':['Math','English','Science','History','Commerce'],
'Mark':[95,88,76,73,93]}
student_object = pd.DataFrame(student)
student_object
Output:
student_object.loc[1]
Output:
Name Abhispa
Roll_No 101
Subject English
Mark 88
Name: 1, dtype: object
Note:
- It has fetched the index ‘1’ record, which will be a series.
student_object.loc[[1,2,3]]
Output:
Note:
- It has fetched the index ‘1’ ,’2′ and ‘3’ records.
- You can specify multiple indexes within an array.
student_object.loc[1:3]
Output:
Note:
- Here I am specifying a range of indexes from ‘1’ to ‘3’ with ‘:’.
student_object.loc[:,'Name':'Subject']
Output:
Note:
- You can specify the range of columns using ‘:’.
student_object.loc[[1,2,3],['Name','Subject']]
Output:
Note:
- You can specify the column and row names within a list.
student_object.loc[:,['Name','Mark']]
Output:
student_object.loc[[1],['Name']]
Output:
Note:
- Fetching a single value.