Pandas dataframe is a very useful data structure.
In this notebook, I will show with examples how to convert Python List to Pandas Dataframe.
import pandas as pd
Let us create a dummy list of stock symbols.
stocks = ['AMC', 'GME', 'BB', 'CLOV', 'PLTR']
Creating Dataframe from list can be achieved using pandas.DataFrame.
df = pd.DataFrame(stocks,columns=['ticker'])
Let us look at our dataframe now.
df.head()
Notice, the "columns" option in the pd.DataFrame code to name the column name. We can also first create dataframe and then add the column names.
df = pd.DataFrame(stocks)
df.head()
By default, Pandas has named the column 0.
Let us rename the column using dataframe.rename.
df.rename(columns={0: "ticker"},inplace=True)
df.head()
Now we can access the column using the column name.
df['ticker']
Notice also the index of dataframe. By default, Pandas sets the index starting from 0. We can print the index information using following piece of code.
df.index
Ofcourse we can use index to access any row value.
df.loc[0]
df.loc[1]
To learn more about accessing rows and columns in Pandas Dataframe, check out Select Pandas Dataframe Rows And Columns Using iloc loc and ix
Another way to set or rename the column names in Pandas Dataframe is using dataframe.columns
df.columns = ['ticker']
df.head()
df.iloc[0]
In the example below, we will convert List of Lists to Dataframe.
Assume we have below list of lists.
stocks = [['AMC', 'GME', 'BB', 'CLOV', 'PLTR'], ['AAPL','GOOGL','AMZN','NFLX','FB']]
pd.DataFrame(stocks)
Notice, our pd.DataFrame command creates the dataframe in wide format. To convert it back to taller format, we can use Pandas dataframe transpose() function.
df = pd.DataFrame(stocks).transpose()
df.head()
Now we can rename the columns.
df.columns = ['Reddit_stocks','Fang_stocks']
df.head()
However Python list of lists could be in following format.
stocks = [['AMC', 'GOOGL'], ['GME', 'AMZN'], ['BB','AMZN'], ['CLOV', 'NFLX'],['PLTR','FB']]
This format is pretty straitforward to convert to Dataframe.
df = pd.DataFrame(stocks,columns=['Reddit_stocks','FANG_stocks'])
df.head()
Also checkout the notebook on How to Convert Python Pandas DataFrame into a List
Related Notebooks
- How to Convert Python Pandas DataFrame into a List
- Convert Pandas DataFrame To Numpy Arrays
- How to Export Pandas DataFrame to a CSV File
- How To Append Rows With Concat to a Pandas DataFrame
- How to Sort Pandas DataFrame with Examples
- Python Pandas String To Integer And Integer To String DataFrame
- How To Read JSON Data Using Python Pandas
- How To Drop One Or More Columns In Pandas Dataframe
- How To Iterate Over Rows In A Dataframe In Pandas