How to create a DataFrame in Python
• 1 minPython 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
Create a DataFrame
We create an empty DataFrame.
# an empty dataframe
df = pd.DataFrame()
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))
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"]})
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"]})
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.