How to create a DataFrame in Python

1 min

Python has a set of tools for Data Science which are among the best on the market.

The Pandas library is the one you will probably use all of the time.

Pandas will help you manipulate DataFrames.

Importing Pandas

We import the pandas library.

import pandas as pd
How to import pandas. The as pd here is just for a better ease-of-use

Create a DataFrame

We create an empty DataFrame.

# an empty dataframe
df = pd.DataFrame()
We create an instance of the pd.DataFrame() class

Create a DataFrame with index

We create a DataFrame with index.

# A dataframe with an index from 0 to 9
df = pd.DataFrame(index=range(0,10))
A DataFrame with index

Create a DataFrame with index and column

Here is the example of creating a DataFrame with one index and one column.

See the index and data parameters.

# A dataframe with an index from 0 to 5 with a column "firstname" of names
df = pd.DataFrame(index=range(0,6), data={"names" : ["James", "Daniel", "Georges", "Bobby", "Jessica", "Aline"]})
A DataFrame with index and one column

Create a DataFrame with index and n columns.

In this example we crate a DataFrame with an index from 0 to 5 with two different columns.

# A dataframe with an index from 0 to 5 with a column "firstname" of names
# and a column "lastname" of lastnames
df = pd.DataFrame(index=range(0,6), data={"firstname" : ["James", "Daniel", "Georges", "Bobby", "Jessica", "Aline"], "lastname" : ["Johnson", "Craig", "Washington", "Freight", "Loretti", "Smith"]})
A DataFrame with an index and two columns

This is how you create a DataFrame !

If you already have data ?

If you already have data, I've created another blog post that will give you a method to read data.

How to read a CSV file in Python using Pandas
The simplest way to read csv file in Python.Using the pandas library we can transform the csv into a workable dataframe object that looks just like an excel sheet.