Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write Python Array into Excel Spread sheet

I am trying to write following array into Excel spreadsheet using Python:

array = [ [a1,a2,a3], [a4,a5,a6], [a7,a8,a9], [a10, a11, a12, a13, a14]]

At spreadsheet array should look:

a1  a4  a7  a10
a2  a5  a8  a11
a3  a6  a9  a12
            a13
            a14

Is anyone can show some Python code to do it? Thank you in advance,

Felix

like image 580
Felix Avatar asked Aug 09 '15 23:08

Felix


People also ask

How do I save a Numpy array to Excel?

Use “savetxt” method of numpy to save numpy array to csv file. CSV files are easy to share and view, therefore it's useful to convert numpy array to csv. CSV stands for comma separated values and these can be viewed in excel or any text editor whereas to view a numpy array object we need python.


2 Answers

Here is one way to do it using the XlsxWriter module:

import xlsxwriter

workbook = xlsxwriter.Workbook('arrays.xlsx')
worksheet = workbook.add_worksheet()

array = [['a1', 'a2', 'a3'],
         ['a4', 'a5', 'a6'],
         ['a7', 'a8', 'a9'],
         ['a10', 'a11', 'a12', 'a13', 'a14']]

row = 0

for col, data in enumerate(array):
    worksheet.write_column(row, col, data)

workbook.close()

Output:

enter image description here

like image 131
jmcnamara Avatar answered Oct 09 '22 09:10

jmcnamara


Use pandas data frame!

import pandas as pd

array = [['a1', 'a2', 'a3'],
         ['a4', 'a5', 'a6'],
         ['a7', 'a8', 'a9'],
         ['a10', 'a11', 'a12', 'a13', 'a14']]

df = pd.DataFrame(array).T
df.to_excel(excel_writer = "C:/Users/Jing Li/Desktop/test.xlsx")

excel_writer is File path in str or existing ExcelWriter object.

like image 41
Jing Li Avatar answered Oct 09 '22 09:10

Jing Li