Home > Back-end >  How to create a dataframe from a list of lists?
How to create a dataframe from a list of lists?

Time:11-28

I need to create a dataframe from a list which contains 10 stocks data in a list.. but the required format is all items should be listed in one column instead of each column for each element. The required format should look like this image below,

enter image description here

I tried this (the entire code),

import openpyxl
import pandas as pd

xl = openpyxl.load_workbook("Stock_sample.xlsx")
sheet1 = xl["Close Price"]

all_cols = sheet1.iter_cols(min_col=2, max_col=10, values_only = True)

all_cols_list = []
for cols in all_cols:
    all_cols_list.append(cols)

df = pd.DataFrame (all_cols_list)
print (df)

the all_cols_list returns a list of list. When I create a df from that list, that returned a dataframe like this below, enter image description here

So, don't know how to do so. please suggest a way to do the required format

CodePudding user response:

Each list inside the list will be a new column. If you convert these lists into a single list, you can get the output you want. You can use:

df=pd.DataFrame([i for sublist in all_cols_list for i in sublist])
  • Related