How to convert a Python list or lists to a pandas DataFrame
The pandas library and DataFrame
pandas is a data analysis software package in Python, which is used for manipulating data. This library contains the DataFrame class.
A pandas DataFrame is a 2D data structure, which is organized in rows and columns in a tabular format. It allows us to store tabular data and perform various operations on that data using different methods.
Creating a DataFrame from a Python list
A Python list is an ordered and changeable collection of data objects. We can create a pandas DataFrame from a Python list. Let's look at the following code to see how we can achieve this.
Syntax
The code snippet given below demonstrates the creation of a pandas DataFrame from a Python list.
df = pandas.DataFrame(list)
Parameter values
pandas: This is the library that contains theDataFrameclass. The line shown above calls the constructor for theDataFrameclass.list: This is a required parameter that needs to be passed to the constructor.
Return value
The DataFrame constructor returns a pandas DataFrame that contains all the elements in a list. In the code snippet given above, the DataFrame instance is stored in df.
Example
Let's look at an example that uses the syntax shown above:
# Importing pandasimport pandas as pd# creating a listls = [1,2,3,4,5]#creating dataframe from listdf = pd.DataFrame(ls)# printing dfprint(df)# creating a listls = [[1,2,3], [4,5,6], [7,8,9]]#creating dataframe from listdf = pd.DataFrame(ls)# printing dfprint(df)
Explanation
- Line 2: We import
pandasaspd. - Line 4: We create a Python list called
ls. - Line 6: We create a Pandas
DataFramecalleddffrom thelslist. - Line 8: We print the
dfDataFrame. We observe thatdfcontains all the elements fromls. - Line 10: We update
lsto make it a list that contains other lists. - Line 12: We create a pandas
DataFramecalleddffrom thelslist. - Line 14: We print the
dfDataFrame. We observe thatdfcontains all the elements fromls.
Free Resources