In Pandas DataFrame .loc() method is used to take the index label and return the row or columns.
.loc() is used to access the groups of rows and columns by using labels or a boolean array.
.loc() method takes only index label and check in dataframe if it exists in the given dataframe it returns the rows, columns or DataFrame.
These are some allowed input for .loc[]:
- Single label e.g., 9 or 'a'. Here 9 is interpreted as a label of the index.
- List or array of labels, e.g.['a','b','c']
- Sliced object with labels.
- Boolean array with the same length of the axis begin sliced.
- Callable function with one argument, that can return valid output for indexing.
Syntax
DataFrame.loc
Return:
It return a scalar dataframe or series.
Example
import pandas as pd
df=pd.DataFrame({'Name':['Rohit','Rahul','Alice','John','Joey'],'Age':[16,17,19,15,14],
'Height':[150.5,167.9,145.7,152.6,148.7]})#Create DataFrame
index = ['1', '2', '3', '4', '5']#Create index
df.index=index
print(df)#print the dataframe
Output:
Name Age Height
1 Rohit 16 150.5
2 Rahul 17 167.9
3 Alice 19 145.7
4 John 15 152.6
5 Joey 14 148.7
result = df.loc['3', 'Name']
result#return the value
Output:
'Alice'
result = df.loc[:, ['Name', 'Age']]
result
Output:
Name | Age | |
---|---|---|
1 | Rohit | 16 |
2 | Rahul | 17 |
3 | Alice | 19 |
4 | John | 15 |
5 | Joey | 14 |