Reputation: 467
I have a bunch of data frames with sales data for different brands. I want to create a function that ultimately makes excel files from the brand specific data frames. Everything works fine except I need to make uniquely named excel files as the output. Here is what I currently have:
def brandOverview(b):
brandWriter = pd.ExcelWriter("Brand.xlsx", engine='xlsxwriter')
b.to_excel(brandWriter, sheet_name='Data')
brandWriter.save()
This works, but ultimately I would like "Brand.xlsx" to be uniquely named for the data frame that is put into the function (b). For example if my dataframe was named "Adidas", brandOverview(Adidas) would output a file named "Adidas.xlsx".
I tried to use:
brandWriter = pd.ExcelWriter((str(b)+".xlsx"), engine='xlsxwriter')
From what I can decipher, this generated a string of all the data in the data frame, ultimately causing an error.
Upvotes: 3
Views: 1730
Reputation: 294258
Your attempt is very close. You only need to alter str(b)
and replace it with something that returns 'Adidas'
in this case and whatever the brand is for any other case. You didn't provide any information about the structure of the dataframes. However, in order for this to work, you need to be able to access 'Adidas'
somewhere in b
. If it isn't in there, you cannot do this. If it is there, then you can. If you didn't produce these dataframes yourself, then you may not know if and where it is. How do you know this dataframe is for 'Adidas'
. Is it in a dictionary? If so, then maybe you should pass the dictionary key with the dataframe, like this:
def brandOverview(b, name):
brandWriter = pd.ExcelWriter(name + ".xlsx", engine='xlsxwriter')
b.to_excel(brandWriter, sheet_name='Data')
brandWriter.save()
Maybe the brand name is in the name attribute of the index:
def brandOverview(b):
brandWriter = pd.ExcelWriter(b.index.name + ".xlsx", engine='xlsxwriter')
b.to_excel(brandWriter, sheet_name='Data')
brandWriter.save()
Maybe the brand name is in the name attribute of the columns:
def brandOverview(b):
brandWriter = pd.ExcelWriter(b.columns.name + ".xlsx", engine='xlsxwriter')
b.to_excel(brandWriter, sheet_name='Data')
brandWriter.save()
first column name:
def brandOverview(b):
brandWriter = pd.ExcelWriter(b.columns[0] + ".xlsx", engine='xlsxwriter')
b.to_excel(brandWriter, sheet_name='Data')
brandWriter.save()
Ultimately, you didn't provide enough information. This should help you out but I'd expect you to follow up with sample data for us to help further.
Upvotes: 2