사소한 Tip . 오류 해결법/python

[pandas / DataFrame] MultiIndex df.to_excel 저장 시 빈 행(row) 삭제하기

Js.Y 2024. 1. 3. 09:22
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)

 

 

참고자료

 

Blank line below headers created when using MultiIndex and to_excel in Python

I am trying to save a Pandas dataframe to an excel file using the to_excel function with XlsxWriter. When I print the dataframe to the terminal then it reads as it should, but when I save it to exc...

stackoverflow.com

 

728x90
반응형