Home > Mobile >  Best way in Pandas to put two lists into a Dataframe and add each list to a separate Excel column
Best way in Pandas to put two lists into a Dataframe and add each list to a separate Excel column

Time:09-05

Presently, I have code that creates a new Pandas Dataframe per list and then prints each list to its own column in Excel.

What would be the way to combine the lists into a single Dataframe and then add each list to its own Excel column?

Code

df_cc = pd.DataFrame({'Captions': cc_list})
wb = load_workbook(path)
ws = wb['Sheet1']

df_fname = pd.DataFrame({'Filename': filename_list})
wb = load_workbook(path)
ws = wb['Sheet1']


# Write to the excel sheet
for index, row in df_cc.iterrows():
    cell = 'C%d'  % (index   2)
    ws[cell] = row[0]

for index, row in df_fname.iterrows():
    cell = 'D%d'  % (index   2)
    ws[cell] = row[0]

CodePudding user response:

This should work. Make sure to install required deps (pip install xlwt).

df = pd.DataFrame({
    'Captions': cc_list,
    'Filename': filename_list
})
df.to_excel('test.xls')
  • Related