Pandas DataFrame is a 2-dimensional labeled data structure like any table with rows and columns. The size and values of the dataframe are mutable,i.e., can be modified. It is the most commonly used pandas object. Pandas DataFrame can be created in multiple ways. Let’s discuss different ways to create a DataFrame one by one. Show DataFrame() function is used to create a dataframe in Pandas. The syntax of creating dataframe is: pandas.DataFrame(data, index, columns) where, data: It is a dataset from which dataframe is to be created. It can be list, dictionary, scalar value, series, ndarrays, etc. index: It is optional, by default the index of the dataframe starts from 0 and ends at the last data value(n-1). It defines the row label explicitly. columns: This parameter is used to provide column names in the dataframe. If the column name is not defined by default, it will take a value from 0 to n-1. Method #0:Creating an Empty DataFrame Python3
Output:
Output
Method #1: Creating Dataframe from Lists Python3
Dataframe created using list Method #2: Creating Pandas DataFrame from lists of lists. Python3
Output:
Method #3: Creating DataFrame from dict of narray/lists Python3
Output: Note: While creating dataframe using dictionary, the keys of dictionary will be column name by default. We can also provide column name explicitly using column parameter. Python3
Output: Python3
Output: Another example to create pandas DataFrame by passing lists of dictionaries and row indexes. Python3
Output: Another example to create pandas DataFrame from lists of dictionaries with both row index as well as column index. Python3
Output: Python3
Output: Method#7: Creating dataframe from series To create a dataframe from series, we must pass series as argument to DataFrame() function. Python3
Method #8: Creating DataFrame from Dictionary of series. Python3
|