728x90
반응형
Multiindex를 갖고 있는 데이터 프레임을 그대로 excel로 떨어트리는 함수를 사용할 경우에 제목 행 바로 아래에 빈 행이 하나 생기게 된다.
이를 해결하기 위한 함수는 아래와 같다.
간단히, 제목만 떼서 저장하고, 이어서 내용에 해당되는 부분만 떼서 2번에 걸쳐 저장하는 함수라 보면 된다.
def save_double_column_df(df, file_name, startrow = 0, **kwargs):
'''Function to save doublecolumn DataFrame, to xlwriter'''
# https://stackoverflow.com/questions/52497554/blank-line-below-headers-created-when-using-multiindex-and-to-excel-in-python
# inputs:
# df - pandas dataframe to save
# xl_writer - book for saving
# startrow - row from wich data frame will begins
# **kwargs - arguments of `to_excel` function of DataFrame`
with pd.ExcelWriter(file_name.format(nm), mode='w') as writer:
df.drop(df.index).to_excel(writer, startrow = startrow, **kwargs)
df.to_excel(writer, startrow = startrow + 1, header = False, **kwargs)
728x90
반응형
'사소한 Tip . 오류 해결법 > python' 카테고리의 다른 글
[python/pickle] pickle data load/read, write (0) | 2024.01.22 |
---|---|
[python/pdf] PDF 수정(페이지 삭제, 병합)하기(PyPDF2) (0) | 2024.01.05 |
[python/PIL] image to pdf convert (0) | 2023.10.17 |
[PIL] 투명한 이미지 만들기(글자만 남기기) / transparent image / remove background (2) | 2023.10.11 |
[python] open() got an unexpected keyword argument 'encoding' / python 3.9 (0) | 2023.09.06 |