What is the Pandas DataFrame.get() method in Python?
Overview
In Python, the get() method is used to get an item object for a given key from the DataFrame. This given key can be either one or more series or DataFrame columns. It takes two argument values, key and default. If the required key does not exist, it returns the default argument value.
Syntax
# SignatureDataFrame.get(key, default=None)
Parameters
key: The object to extract.default: The value to return in a case thekeydoes not exist.
Return value
It returns a value according to the argument key.
Note:When key does not exist
- If
defaultis set, it returns the default value
- Otherwise, it returns
None
Example
In the code snippets below, we use the DataFrame.get() method to extract DataFrame values as series or Columns of DataFrame. Here listed three cases:
- Extract single column
- Extract multiple columns
- The column does not exist
Extract single column
main.py
employee.csv
# importing pandas as pdimport pandas as pd# Creating the dataframedf = pd.read_csv("employee.csv")# applying get() functionprint(df.get(["Name"]))
main.py
employee.csv
# importing pandas as pdimport pandas as pd# Creating the dataframedf = pd.read_csv("employee.csv")# applying get() functionprint(df.get(["Name","Designation","Total"]))
main.py
employee.csv
# importing pandas as pdimport pandas as pd# Creating the dataframedf = pd.read_csv("employee.csv")# applying get() functionprint(df.get(key="ID", default="Key doesn't exist"))