Getting the column names of a DataFrame

columns_of_dataframe

Skill - Getting the column names of DataFrame

Table of Contents

Skills Required

Please make sure to have all the skills mentioned above to understand and execute the code mentioned below. Go through the above skills if necessary for reference or revision

Pandas is a python library.
DataFrame is a data structure provided by the pandas library.

Please go through Pandas DataFrame Basics to learn the basics of pandas DataFrame.

In this post we will learn how to get the column names of a DataFrame using the columns attribute

import pandas as pd
# create a dataframe
x = {
	"Name": ["Harris", "Miss. Elizabeth"],
	"Age": [22, 58],
	"Sex": ["male", "female"]
	}
df = pd.DataFrame(x)

# print the columns of DataFrame. This will return an index object
print(df.columns)
# Index([u'Age', u'Name', u'Sex'], dtype='object')

# print the list of columns of the DataFrame by passing it through 'list' function
print(list(df.columns))
# ['Age', 'Name', 'Sex']

Video

Watch video on this post here

Online Interpreter

Although we recommend to practice the above examples in Visual Studio Code, you can run these examples online at https://www.tutorialspoint.com/execute_python_online.php

References


Table of Contents

Comments