是否有一种方法可以从熊猫数据框中的单元格值动态命名Excel工作表?
这是我所拥有的:
#dataframe cell i want to work as sheet name is here
df_storename = df_store.loc[1, 'Store']
writer = pd.ExcelWriter('payroll.xlsx', engine='xlsxwriter')
# Convert the dataframe to an XlsxWriter Excel object.
df_store.to_excel(writer, sheet_name=df_storename)
workbook = writer.book
worksheet1 = writer.sheets[df_storename]
worksheet2 = workbook.add_worksheet('One-on-One')
chart = workbook.add_chart({'type': 'column'})
chart1 = workbook.add_chart({'type': 'column'})
chart.add_series({'values': '=df_storename!$F$0:$F$9', 'name':
'Service Sales', 'categories':
'=df_storename!$C$2:$C$11'})
chart1.add_series({'values': '=df_storename!$P$0:$P$9',
'name': 'Paid Back Bar %', 'categories':
'=df_storename!$C$2:$C$11'})
答案 0 :(得分:2)
执行此操作的最佳方法是使用add_series()
中的列表语法,而不是A1:C8
范围语法。例如:
import pandas as pd
# Create a Pandas dataframe from some data.
df_store = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})
df_storename = 'My Storename'
writer = pd.ExcelWriter('payroll.xlsx', engine='xlsxwriter')
# Convert the dataframe to an XlsxWriter Excel object.
df_store.to_excel(writer, sheet_name=df_storename)
workbook = writer.book
worksheet1 = writer.sheets[df_storename]
worksheet2 = workbook.add_worksheet('One-on-One')
chart = workbook.add_chart({'type': 'column'})
chart.add_series({'name': 'Service Sales',
'categories': [df_storename, 1, 0, 7, 0],
'values': [df_storename, 1, 1, 7, 1]})
worksheet2.insert_chart('D2', chart)
writer.save()
输出:
这样,您可以使用数据框的大小来设置要绘制的单元格范围。有关更实际的示例,请参见XlsxWriter Pandas chart examples。