How to create a DataFrame in Python?


Dataframe is a 2D data structure. Dataframe is used to represent data in tabular format in rows and columns. It is like a spreadsheet or a sql table. Dataframe is a Pandas object.

To create a dataframe, we need to import pandas. Dataframe can be created using dataframe() function. The dataframe() takes one or two parameters. The first one is the data which is to be filled in the dataframe table. The data can be in form of list of lists or dictionary of lists. In case of list of lists data, the second parameter is the columns name.

Create dataframe from dictionary of lists

import pandas as pd

data={'Name':['Karan','Rohit','Sahil','Aryan'],'Age':[23,22,21,24]}

df=pd.dataframe(data)

df #print the dataframe

The output will be a table having two columns named 'Name' and 'Age' with the provided data fed into the table.

Create dataframe from list of lists

import pandas as pd

data=[['Karan',23],['Rohit',22],['Sahil',21],['Aryan',24]]

df=pd.dataframe(data,columns=['Name','Age'])

df

This also gives the same output. The only difference is in the form in which the data is provided. Since the columns names are not specified earlier, it is needed to pass column names as arguments in the dataframe() function.

Create customized index dataframe

import pandas as pd

data={'Name':['Karan','Rohit','Sahil','Aryan'],'Age':[23,22,21,24]}

df=pd.dataframe(data,index=['No.1','No.2','No.3','No.4'])

df

This creates the same dataframe with indexes as mentioned in the index list.

Updated on: 25-Aug-2023

32K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements