Different ways to create Pandas Dataframe -What is the method for creating a data frame?
#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
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.
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.
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'])
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)
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.