How to Create a Pandas Sample Dataframe

0

In this post, you will learn about how to create a Pandas dataframe with some sample data. The following represent two different techniques using which one can create the Pandas Dataframe:

  • Create Dataframe without using Numpy Array
  • Create Dataframe using Numpy Array

Create Dataframe without using Numpy Array

Here is the python code for creating a Pandas dataframe without using Numpy array:

import pandas as pd
#
# Create dataframe
#
df = pd.DataFrame([['Ajitesh', 84, 183, 'no'], 
                   ['Shailesh', 79, 186, 'yes'], 
                   ['Seema', 67, 158, 'yes'], 
                   ['Nidhi', 52, 155, 'no']])
#
# Assign column names
#
df.columns = ['name', 'weight', 'height', 'smoke_or_not']
#
# Print dataframe
#
df

Create Dataframe using Numpy Array

Here is the code for creating a dataframe using Numpy array. Note the usage of np.array used for creating an instance of Numpy Ndarray.

import numpy as np
#
# Create dataframe
#
df = pd.DataFrame(np.array([['Ajitesh', 84, 183, 'no'], 
                   ['Shailesh', 79, 186, 'yes'], 
                   ['Seema', 67, 158, 'no'], 
                   ['Nidhi', 52, 155, 'no']]))
#
# Assign column names
#
df.columns = ['name', 'weight', 'height', 'smoke_or_not']
#
# Print dataframe
#
df

The following will be printed:

Pandas Dataframe using Array
Fig 1. Pandas Dataframe using Array
Ajitesh Kumar
Follow me
Share.

Leave A Reply

Time limit is exhausted. Please reload the CAPTCHA.