これで、pandasデータフレームのピボットテーブルのエクスポートトピックに戻ったので、エクスポートのためのより良いライブラリが見つかりました。 Openpyxl! openpyxlを使用すると、あらかじめ定義されたExcelテンプレートを開くことができるので、不要なxlsxwriterのバグに対処する必要はありません。次に、openpyxlのサンプルコードを示します。
import openpyxl
from openpyxl import load_workbook
workbook.active = 0
worksheet = workbook.active
worksheet.title = 'XYZ'
#check length of df
depth_df_2 = len(merged_plz_all)
#call special method to comfortably write the dataframe below your
#predefined header
update_range(workbook.active,merged_plz_all,cell_range =
'A18:'+str(spaltenindex[len(merged_plz_all.columns)])+str(depth_df_2+17))
workbook.save('yourNicelyLookingPivotTable.xlsx')
これは別のstackoverflowスレッドで見つかった必要なupdate_rangeメソッドです。私は残念ながらそれをブックマークしていませんでしたので、私はupdate_rangeメソッドの起点を提供してくれないことを許してください。個人的に私はこのメソッドがライブラリopenpyxlそのものの一部でなければならないことを知っています!
def update_range(worksheet, data, cell_range=None, named_range=None):
"""
Updates an excel worksheet with the given data.
:param worksheet: an excel worksheet
:param data: data used to update the worksheet cell range (list, tuple, np.ndarray, pd.Dataframe)
:param cell_range: a string representing the cell range, e.g. 'AB12:XX23'
:param named_range: a string representing an excel named range
"""
def clean_data(data):
if not isinstance(data, (list, tuple, np.ndarray, pd.DataFrame)):
raise TypeError('Invalid data, data should be an array type iterable.')
if not len(data):
raise ValueError('You need to provide data to update the cells')
if isinstance(data, pd.DataFrame):
data = data.values
elif isinstance(data, (list, tuple)):
data = np.array(data)
return np.hstack(data)
def clean_cells(worksheet, cell_range, named_range):
# check that we can access a cell range
if not any((cell_range, named_range) or all((cell_range, named_range))):
raise ValueError('`cell_range` or `named_range` should be provided.')
# get the cell range
if cell_range:
try:
cells = np.hstack(worksheet[cell_range])
except (CellCoordinatesException, AttributeError):
raise ValueError('The cell range provided is invalid, cell range must be in the form XX--[:YY--]')
else:
try:
cells = worksheet.get_named_range(named_range)
except (TypeError):
raise ValueError('The current worksheet {} does not contain any named range {}.'.format(
worksheet.title,
named_range))
# checking that we have cells to update, and data
if not len(cells):
raise ValueError('You need to provide cells to update.')
return cells
cells = clean_cells(worksheet, cell_range, named_range)
data = clean_data(data)
# check that the data has the same dimension as cells
if len(cells) != data.size:
raise ValueError('Cells({}) should have the same dimension as the data({}).'.format(len(cells), data.size))
for i, cell in enumerate(cells):
cell.value = data[i]
'T-Class'は' columns'オブジェクトの名前です。 'to_excel'は' columns'オブジェクトの名前の書き出しを邪魔しません。この正確なフォーマットが必要な場合は、カスタム書込みを行う必要があります。完全に実行可能ですが、 'to_excel'オプションでは簡単には達成できません。 – piRSquared
サンプルコードやヒントを使って、この形式を行う方法を教えてください。 – MBUser