Pandas naming multiple sheets according to list of lists
<p>First time I post here and I am rather a newbie. </p>

<p>Anyhow, I have been playing around with Pandas and Numpy to make some calculations from Excel.</p>

<p>Now I want to create an .xlsx file to which I can output my results and I want each sheet to be named after the name of the dataframe that is being outputted.</p>

<p>This is my code, I tried a couple of different solutions but I can't figure how to write it. </p>

<p>In the code you can see that save_excel just makes numbered sheets (and it works great) and save_excelB tries to do what I am describing it but I can't get it to work.</p>

<pre><code>from generate import A,b,L,dr,dx
from pandas import DataFrame as df
from pandas import ExcelWriter as ew

A=df(A) #turning numpy arrays into dataframes
b=df(b)
L=df(L)
dr=df(dr)
dx=df(dx)

C=[A,b,L,dr,dx] #making a list of the dataframes to iterate through


def save_excel(filename, item):
    w=ew(filename)
    for n, i in enumerate(item):
        i.to_excel(w, "sheet%s" % n, index=False, header=False)
    w.save()

def save_excelB(filename, item):
    w=ew(filename)
    for name in item:
        i=globals()[name]
        i.to_excel(w, sheet_name=name, index=False, header=False)
    w.save()
</code></pre>

<p>I run both in the same way I call the function and I add the file name and for item I insert the list C I have made. </p>

<p>So it would be: </p>

<pre><code>save_excelB("file.xlsx", C) 
</code></pre>

<p>and this is what I get </p>

<pre><code>TypeError: 'DataFrame' objects are mutable, thus they cannot be hashed
</code></pre>

<p>You need to pass string literals of data frame names in your function and not actual data frame objects:</p>

<pre><code>C = ['A', 'b', 'L', 'dr', 'dx']

def save_excelB(filename, item):
    w=ew(filename)
    for name in item:
        i=globals()[name]
        i.to_excel(w, sheet_name=name, index=False, header=False)
    w.save()

save_excelB("file.xlsx", C) 
</code></pre>

<p>You can even dynamically create <em>C</em> with all dataframes currently in global environment by checking items that are pandas data frame class type:</p>

<pre><code>import pandas as pd
...

C = [i for i in globals() if type(globals()[i]) is pd.core.frame.DataFrame]
</code></pre>

python excel pandas