Signup/Sign In

Pandas DataFrame get() Method

In this tutorial, we will learn the Python pandas DataFrame.get() method. This method is used to get the item from the object for a given key (ex: DataFrame column). It returns the default value if the specified key not found.

The below shows the syntax of the DataFrame.get() method.

Syntax

DataFrame.get(key, default=None)

Parameter:

key: object

Example: Getting the column of the DataFrame using the DataFrame.get() Method

We can extract the column from the DataFrame by defining column name as the key in the DataFrame.get() method.

#importing pandas as pd
import pandas as pd
#creating DataFrame
df=pd.DataFrame({"Name":["Navya","Vindya"],"Age":[25,24],"Education":["M.Tech","Ph.d"],"YOP":[2019,None]})
print("------The DataFrame is--------")
print(df)
print("-----Getting single columns-----")
print(df.get("Age"))

Once we run the program we will get the following output.


------The DataFrame is--------
Name Age Education YOP
0 Navya 25 M.Tech 2019.0
1 Vindya 24 Ph.d NaN
-----Getting single columns-----
0 25
1 24
Name: Age, dtype: int64

Example: Getting the multiple columns of the DataFrame using the DataFrame.get() Method

We can extract the multiple columns from the DataFrame by defining column names as the keys in the DataFrame.get() method.

#importing pandas as pd
import pandas as pd
#creating DataFrame
df=pd.DataFrame({"Name":["Navya","Vindya"],"Age":[25,24],"Education":["M.Tech","Ph.d"],"YOP":[2019,None]})
print("------The DataFrame is--------")
print(df)
print("-----Getting multiple columns-----")
print(df.get(["Name","Education"]))

Once we run the program we will get the following output.


------The DataFrame is--------
Name Age Education YOP
0 Navya 25 M.Tech 2019.0
1 Vindya 24 Ph.d NaN
-----Getting multiple columns-----
Name Education
0 Navya M.Tech
1 Vindya Ph.d

Example: Getting the column of the DataFrame using the DataFrame.get() method with default the Method

It returns the default value if the specified key not found.

#importing pandas as pd
import pandas as pd
#creating DataFrame
df=pd.DataFrame({"Name":["Navya","Vindya"],"Age":[25,24],"Education":["M.Tech","Ph.d"],"YOP":[2019,None]})
print("------The DataFrame is--------")
print(df)
print("-----Getting columns-----")
print(df.get("skills",default="Specified key is not mentioned"))

Once we run the program we will get the following output.


------The DataFrame is--------
Name Age Education YOP
0 Navya 25 M.Tech 2019.0
1 Vindya 24 Ph.d NaN
-----Getting columns-----
Specified key is not mentioned

Conclusion

In this tutorial, we learned the Python pandas DataFrame.get() method. We learned the syntax and by applying this method on the DataFrame we understood the DataFrame.get() method.



About the author:
I like writing about Python, and frameworks like Pandas, Numpy, Scikit, etc. I am still learning Python. I like sharing what I learn with others through my content.