Search code examples
pythonarraysexcelpandasexport-to-excel

How to export 2d array into Excel sheets using python using Pandas data frame?


I am trying to write a array into Excel spreadsheet using Python

the array looks something like this:

array = [ [N1,N2,N3], [N4,N5,N6], [N7,N8,N9], [N10, N11, N12]]

As the spread sheet should look like this:

N1  N2  N3 
N4  N5  N6 
N7  N8  N9  
N10 N11 N12

However my code:

result = pd.DataFrame(array).T   
result.to_excel('clean_data.xlsx')

give the result of

N1  N4  N7 N10
N2  N5  N8 N11
N3  N6  N9 N12

Can anyone show the Python code to do it ? Thank you in advance.


Solution

  • You transpose the matrix/array by doing the

    .T

    thus your results is orientated differently:

    simply doing without the transformation gives your desired result:

    import pandas as pd
    
    array = [ ["N1","N2", "N3"], ["N4", "N5","N6"], ["N7","N8","N9"], ["N10", "N11", "N12"]]
    result = pd.DataFrame(array) #remove the .T here
    result.to_excel('clean_data.xlsx')