I am trying to write a function that accepts data and filename as arguments, with the former being the data that is to be saved under the name of the latter. I would like to keep it inside a function and not resort to list comprehension as I did to make OutWriter3
work via test3
.
import numpy as np
import pandas as pd
data_a = np.random.randint(100, size=21)
data_b = np.random.randint(200, size=21)
def OutWriter1(data, filename):
for d, f in zip(data, filename):
out = pd.DataFrame(d)
return out.to_excel(f, header=False, index=False)
def OutWriter2(data, filename):
out = []
for d, f in zip(data, filename):
df = pd.DataFrame(d)
out.append(df)
out = pd.DataFrame(out)
return out.to_excel(f, header=False, index=False)
def OutWriter3(data, filename):
out = pd.DataFrame(data)
return out.to_excel(filename, header=False, index=False)
test1 = OutWriter1([data_a, data_b], ['data_a_1.xlsx', 'data_b_1.xlsx'])
test2 = OutWriter2([data_a, data_b], ['data_a_2.xlsx', 'data_b_2.xlsx'])
test3 = [OutWriter3(i, j) for i, j in zip([data_a, data_b], ['data_a_3.xlsx', 'data_b_3.xlsx'])]
data_a_1.xlsx
from OutWriter1
is correct but data_b_1.xlsx
is nonexistent, data_a_2.xlsx
is entirely wrong and data_b_2.xlsx
is also nonexistent. However, data_a_3.xlsx
and data_b_3.xlsx
are correct.
Inspired by another question, I also tried to save data_a
and data_b
as sheets within a single Excel file without any luck (AttributeError: 'list' object has no attribute 'write'
).
def OutWriter4(data, filename):
data = pd.DataFrame(data)
with pd.ExcelWriter(filename) as writer:
for n, df in enumerate(data):
df.to_excel(writer, 'sheet%s' % n)
writer.save()
test4 = OutWriter4([data_a, data_b], ['data_a_4.xlsx', 'data_b_3.xlsx'])
- Is there an elegant way to create a function that creates Excel files provided the data and filename?
- Is there also an elegant way to create a function that writes the different data to assigned sheets within a single Excel file?