Pandas DataFrame.keys
Pandas DataFrame.keys
The DataFrame.keys method in pandas is used to retrieve the column labels (names) of a DataFrame. It is a shorthand for accessing the column labels using the columns attribute.
Syntax
The syntax for DataFrame.keys is:
DataFrame.keys()Here, DataFrame refers to the pandas DataFrame whose column labels are being retrieved.
Returns
A pandas Index object containing the column labels of the DataFrame.
Examples
Retrieving Column Labels
Use keys to get the column labels of a DataFrame.
Python Program
import pandas as pd
# Create a DataFrame
data = {
'Name': ['Arjun', 'Ram', 'Priya'],
'Age': [25, 30, 35],
'Salary': [70000.5, 80000.0, 90000.0]
}
df = pd.DataFrame(data)
# Get the column labels
print("Column Labels:")
print(df.keys())Output
Column Labels:
Index(['Name', 'Age', 'Salary'], dtype='object')Accessing Column Labels as a List
Convert the result of keys to a list for easier manipulation.
Python Program
import pandas as pd
# Create a DataFrame
data = {
'Name': ['Arjun', 'Ram', 'Priya'],
'Age': [25, 30, 35],
'Salary': [70000.5, 80000.0, 90000.0]
}
df = pd.DataFrame(data)
# Get the column labels as a list
print("Column Labels as List:")
column_labels = list(df.keys())
print(column_labels)Output
Column Labels as List:
['Name', 'Age', 'Salary']Iterating Over Column Labels
Iterate through the column labels using keys.
Python Program
import pandas as pd
# Create a DataFrame
data = {
'Name': ['Arjun', 'Ram', 'Priya'],
'Age': [25, 30, 35],
'Salary': [70000.5, 80000.0, 90000.0]
}
df = pd.DataFrame(data)
# Iterate over column labels
print("Iterating Over Column Labels:")
for key in df.keys():
print(key)Output
Iterating Over Column Labels:
Name
Age
SalaryComparing keys and columns
The keys method is equivalent to the columns attribute. Both return the column labels.
Python Program
import pandas as pd
# Create a DataFrame
data = {
'Name': ['Arjun', 'Ram', 'Priya'],
'Age': [25, 30, 35],
'Salary': [70000.5, 80000.0, 90000.0]
}
df = pd.DataFrame(data)
# Compare keys() and columns
print("Using keys():")
print(df.keys())
print("\nUsing columns:")
print(df.columns)Output
Using keys():
Index(['Name', 'Age', 'Salary'], dtype='object')
Using columns:
Index(['Name', 'Age', 'Salary'], dtype='object')Summary
In this tutorial, we explored the DataFrame.keys method in pandas. Key takeaways include:
- Using
keysto retrieve the column labels of a DataFrame. - Converting the result to a list for easier manipulation.
- Iterating over the column labels.
- Understanding that
keysis equivalent tocolumns.
The DataFrame.keys method is a simple and effective way to access column labels in pandas DataFrames.