Dataframe.get() in Pandas with examples
In this tutorial, we will learn how to use the get() method in pandas. This method is used to retrieve an item for an object for a given key which is basically the column of a data frame. One or more items can be obtained. This method is one of the commonly used methods with data frames. So, let us understand this method by beginning the tutorial.
Parameters of Dataframe.get() method
This method has only one argument. It is given below
key: This defines the object to be returned. Values can be one or many.
Dataframe
Let us consider the following data frame. The data frame consists of data of 7 people with the details of SNO, Name, Age, Weight, Gender, Height. This data frame is used for the demonstration of the get() method.
import pandas as p data1 = { 'SNO':[1,2,3,4,5,6,7,], 'Name':['0aa','1bb','2cc','3dd','4ee','5ff','6gg'], 'Age':[34,78,98,21,54,22,18], 'Weight':[57.78,40.0,78.3,90.9834,25.00,98,67], 'Gender':['M','M','F','M','F','F','F'], 'Height':[3,4,5,6,5.3,4.9,6] } d1 = p.DataFrame(data1) print(d1)
OUTPUT:
SNO Name Age Weight Gender Height 0 1 0aa 34 57.7800 M 3.0 1 2 1bb 78 40.0000 M 4.0 2 3 2cc 98 78.3000 F 5.0 3 4 3dd 21 90.9834 M 6.0 4 5 4ee 54 25.0000 F 5.3 5 6 5ff 22 98.0000 F 4.9 6 7 6gg 18 67.0000 F 6.0
Using Dataframe.get() method with only one key
import pandas as p data1 = { 'SNO':[1,2,3,4,5,6,7,], 'Name':['0aa','1bb','2cc','3dd','4ee','5ff','6gg'], 'Age':[34,78,98,21,54,22,18], 'Weight':[57.78,40.0,78.3,90.9834,25.00,98,67], 'Gender':['M','M','F','M','F','F','F'], 'Height':[3,4,5,6,5.3,4.9,6] } d1 = p.DataFrame(data1) print(d1.get("Name"))
OUTPUT:
0 0aa 1 1bb 2 2cc 3 3dd 4 4ee 5 5ff 6 6gg Name: Name, dtype: object
Here, we used the key as the Name column and the output consists of Name column.
Using with multiple keys
import pandas as p data1 = { 'SNO':[1,2,3,4,5,6,7,], 'Name':['0aa','1bb','2cc','3dd','4ee','5ff','6gg'], 'Age':[34,78,98,21,54,22,18], 'Weight':[57.78,40.0,78.3,90.9834,25.00,98,67], 'Gender':['M','M','F','M','F','F','F'], 'Height':[3,4,5,6,5.3,4.9,6] } d1 = p.DataFrame(data1) print(d1.get(["Age","Weight"]))
OUTPUT:
Age Weight 0 34 57.7800 1 78 40.0000 2 98 78.3000 3 21 90.9834 4 54 25.0000 5 22 98.0000 6 18 67.0000
Here, the keys were specified as Age and Weight in a list and the output consists of only these columns.
Also read: How to create an empty DataFrame with column names in Python?
Leave a Reply