Pandas DataFrame keys() method with examples

Spread the love

The pandas keys() method returns the info axis for the pandas object. If it is series then it returns the index and If it is dataframe then it returns the columns.

Syntax –

dataframe.keys()

Examples –

1 . Using keys() method to get the column names –

Let’s read a dataset to work with.

import pandas as pd

url = 'https://raw.githubusercontent.com/bprasad26/lwd/master/data/clothing_store_sales.csv'
df = pd.read_csv(url)
df.head()

Now we can use the keys() method to get the column names.

df.keys()
#output
Index(['Customer', 'Type of Customer', 'Items', 'Net Sales',
       'Method of Payment', 'Gender', 'Marital Status', 'Age'],
      dtype='object')

2 . Using keys() method to find the index of a pandas series –

Let’s create a pandas series.

cust_age = df['Age']

Now we can use the keys() method to get the index of this series.

cust_age.keys()
#output
RangeIndex(start=0, stop=100, step=1)

Rating: 1 out of 5.

Leave a Reply