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


# Signature
DataFrame.get(key, default=None)

Parameters

  • key: The object to extract.
  • default: The value to return in a case the key does not exist.

Return value

It returns a value according to the argument key.

Note:
When key does not exist
  • If default is 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:

  1. Extract single column
  2. Extract multiple columns
  3. The column does not exist

Extract single column

main.py
employee.csv
# importing pandas as pd
import pandas as pd
# Creating the dataframe
df = pd.read_csv("employee.csv")
# applying get() function
print(df.get(["Name"]))
  • Line 4: We use read_csv() to read employee.csv. It returns the employee dataset as Pandas DataFrame.
  • Line 6: We get the "Name" column as series.

Extract multiple columns

main.py
employee.csv
# importing pandas as pd
import pandas as pd
# Creating the dataframe
df = pd.read_csv("employee.csv")
# applying get() function
print(df.get(["Name","Designation","Total"]))
  • Line 4: We use read_csv() to read employee.csv. It returns the employee dataset as Pandas DataFrame df.
  • Line 6: We get multiple columns as new pandas DataFrame.

The column does not exist

main.py
employee.csv
# importing pandas as pd
import pandas as pd
# Creating the dataframe
df = pd.read_csv("employee.csv")
# applying get() function
print(df.get(key="ID", default="Key doesn't exist"))
  • Line 4: We use read_csv() to read employee.csv. It returns the employee dataset as Pandas DataFrame df.
  • Line 6: We get the "ID" feature from employee dataset. When it does not exist, it returns the default argument value Key doesn’t exist.

Free Resources