Go Back

Different ways to create Pandas Dataframe -What is the method for creating a data frame?

12/6/2021
All Articles

#python #code data #pandas #create print #demonstrate pandas #dataframe #ways python code #creating lists initialize passing creates dataframe #create pandas dataframe to create different ways

Different ways to create Pandas Dataframe -What is the method for creating a data frame?

Different ways to create Pandas Datafram

Pandas is quite flexible in terms of the ways to create a dataframe. we can see 4 different ways that can be used for creating a dataframe.

1. Csv or excel file

Csv is one of most frequently used file formats. Thus, the first and foremost method for creating a dataframe is by reading a csv file which is straightforward operation in Pandas. We just need to give the file path to the read_csv function.

df = pd.read_csv("CardioGoodFitness.csv")

2. Numpy arrays

Since a dataframe can be considered as a two-dimensional data structure, we can use a two-dimensional numpy array to create a dataframe.

import pandas as pd
import numpy as npA = np.random.randint(10, size=(4,3))A
array([[9, 2, 0],        
       [4, 3, 0],        
       [2, 3, 1],        
       [7, 1, 3]])
df = pd.DataFrame(A, columns=['cola', 'colb', 'colc'])

 

3. Dictionary

Python dictionaries are also commonly used for creating dataframes. The keys represent the column names and the rows are filled with the values.

 

dict_a = {
'col_a': [1,8,7,8],
'col_b': [18,4,7,8],
'col_c': [16,5,9,10]
}df = pd.DataFrame(dict_a)

4. List

List is a built-in data structure in Python. It is represented as a collection of data points in square brackets. Lists can be used to store any data type or a mixture of different data types.

df = pd.DataFrame(lst_a, columns=['Name', 'Age', 'Height', 'Grade']

Thank you for reading. Please let me know if you have any feedback.

Article