You can convert a list object to a Python DataFrame columns using the insert() or assign() DataFrame methods as shown below:
your_df = your_df.assign(lst_name = [lst_values])
#or
your_df.insert(location, column_name, lst_values)
Create example data
We’ll start by creating a simply Python list and a DataFrame. Feel free to use these to follow along with this tutorial.
import pandas as pd
# create list object
telesales = [26, 13, 183, 18]
#create DataFRame object
channel = ['B2B', 'B2C', 'Retail', 'Online']
sales_dict = {
'direct' : [45, 187, 54, 57],
'indirect' : [674, 634, 581, 375]
}
sales_df = pd.DataFrame (sales_dict, index= area)
List into empty dataframe
We can easily create a new DataFrame into which we’ll append our list object:
sales_df_1 = pd.DataFrame (telesales, columns = ['telesales'])
Note that we used the columns parameter to define the column names.
Alternatively, we can assign the list element values to an empty DataFrame, in this case the name of the list becomuns the column name:
sales_df_1= sales_df_1.assign(telesales = [26, 13, 183, 18])
Both will render the same result:
print(sales_df_1)
telesales | |
---|---|
0 | 26 |
1 | 13 |
2 | 183 |
3 | 18 |
Append a list as a Pandas DataFrame column
We can also assign one or multiple lists as columns /Series in a an existing DataFrame. Here’s a simple example that uses the pretty straightforward insert DataFrame method:
sales_df.insert(loc = 2,column = 'telesales', value = telesales)
Alternatively, using assign the list as a DataFrame column:
sales_df = sales_df.assign(telesales = [26, 13, 183, 18])
In both ways, we accomplished the same result – the list was added as a column:
direct | indirect | telesales | |
---|---|---|---|
B2B | 45 | 674 | 26 |
B2C | 187 | 634 | 13 |
Retail | 54 | 581 | 183 |
Online | 57 | 375 | 18 |
Add list as a DataFrame row
You might want to append your list as a DataFrame row. This is accomplished using the loc indexer:
row_lst = [36, 46, 78]
sales_df.loc['Distributors'] = row_lst