ProgramingTip

Jupyter 노트북은 판다 테이블 2 개를 나란히 표시합니다.

bestdevel 2020. 11. 19. 21:50
반응형

Jupyter 노트북은 판다 테이블 2 개를 나란히 표시합니다.


두 개의 pandas 데이터 프레임이 있으므로 Jupyter 노트북에 표시하고 싶습니다.

다음과 같이합니다.

display(df1)
display(df2)

아래에 하나씩 표시합니다.

여기에 이미지 설명 입력

첫 번째 데이터 프레임의 오른쪽에 두 번째 데이터 프레임을 갖고 싶습니다. 비슷한 질문이 있지만, 사람이 그들 사이의 차이를 보여주는 하나의 dataframe에서 그들을 병합하여 하나 만족이 것 같습니다 .

이것은 나를 위해 작동하지 않습니다. 제 경우에는 데이터 프레임이 완전히 다른 (비교할 수없는 요소)를 가지고 있습니다. 따라서 나의 주요 목표는 공간을 절약하는 것입니다.


출력 코드의 CSS를 재정의 할 수 있습니다. flex-direction: column기본적으로 사용 합니다. row대신 변경해 . 예를 들면 다음과 같습니다.

import pandas as pd
import numpy as np
from IPython.display import display, HTML

CSS = """
.output {
    flex-direction: row;
}
"""

HTML('<style>{}</style>'.format(CSS))

Jupyter 이미지

물론 원하는대로 CSS를 추가로 사용자 정의 할 수 있습니다.

한 셀의 출력 만 대상으로 지정 선택 하려는 대상으로 선택 합니다. 예를 들어,이 코드는 노트북에서 5 번째 셀의 출력 CSS를 수정합니다.:nth-child()

CSS = """
div.cell:nth-child(5) .output {
    flex-direction: row;
}
"""

나는 생성 할 수있는 함수를 작성하게 예시한다.

from IPython.display import display_html
def display_side_by_side(*args):
    html_str=''
    for df in args:
        html_str+=df.to_html()
    display_html(html_str.replace('table','table style="display:inline"'),raw=True)

사용 예 :

df1 = pd.DataFrame(np.arange(12).reshape((3,4)),columns=['A','B','C','D',])
df2 = pd.DataFrame(np.arange(16).reshape((4,4)),columns=['A','B','C','D',])
display_side_by_side(df1,df2,df1)

여기에 이미지 설명 입력


pandas 0.17.1DataFrames의 전국 에서 시작 하여 pandas 스타일링 방법을 직접 만들 수 있습니다.

두 개의 DataFrame을 나란히 표시 한 ntg answer 에서 제안한 set_table_attributes인수와 함께 합니다 . 이것은 두 개의 객체 를 반환 합니다. 정렬 된 데이터 프레임을 표시하려는 IPython 메소드 통해 결합 된 HTML 표현을 전달하면 됩니다.

"style='display:inline'"Stylerdisplay_html

이 방법을 사용하면 다른 스타일 옵션을 더 쉽게 추가 할 수 있습니다. 여기의 요청에 따라, 캡션을 추가하는 방법은 여기 :

import numpy as np
import pandas as pd   
from IPython.display import display_html 

df1 = pd.DataFrame(np.arange(12).reshape((3,4)),columns=['A','B','C','D',])
df2 = pd.DataFrame(np.arange(16).reshape((4,4)),columns=['A','B','C','D',])

df1_styler = df1.style.set_table_attributes("style='display:inline'").set_caption('Caption table 1')
df2_styler = df2.style.set_table_attributes("style='display:inline'").set_caption('Caption table 2')

display_html(df1_styler._repr_html_()+df2_styler._repr_html_(), raw=True)

캡션이있는 정렬 된 데이터 프레임 팬더 스타일러


다음은 제가 지난번에 만난 Jake Vanderplas의 솔루션입니다.

import numpy as np
import pandas as pd

class display(object):
    """Display HTML representation of multiple objects"""
    template = """<div style="float: left; padding: 10px;">
    <p style='font-family:"Courier New", Courier, monospace'>{0}</p>{1}
    </div>"""

    def __init__(self, *args):
        self.args = args

    def _repr_html_(self):
        return '\n'.join(self.template.format(a, eval(a)._repr_html_())
                     for a in self.args)

    def __repr__(self):
       return '\n\n'.join(a + '\n' + repr(eval(a))
                       for a in self.args)

카드 : https://github.com/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/03.08-Aggregation-and-Grouping.ipynb


내 솔루션은 CSS 해킹없이 HTML로 테이블을 작성하고 출력합니다.

import pandas as pd
from IPython.display import display,HTML

def multi_column_df_display(list_dfs, cols=3):
    html_table = "<table style='width:100%; border:0px'>{content}</table>"
    html_row = "<tr style='border:0px'>{content}</tr>"
    html_cell = "<td style='width:{width}%;vertical-align:top;border:0px'>{{content}}</td>"
    html_cell = html_cell.format(width=100/cols)

    cells = [ html_cell.format(content=df.to_html()) for df in list_dfs ]
    cells += (cols - (len(list_dfs)%cols)) * [html_cell.format(content="")] # pad
    rows = [ html_row.format(content="".join(cells[i:i+cols])) for i in range(0,len(cells),cols)]
    display(HTML(html_table.format(content="".join(rows))))

list_dfs = []
list_dfs.append( pd.DataFrame(2*[{"x":"hello"}]) )
list_dfs.append( pd.DataFrame(2*[{"x":"world"}]) )
multi_column_df_display(2*list_dfs)

많이


이것은 @nts의 답변에 헤더를 추가합니다.

from IPython.display import display_html

def mydisplay(dfs, names=[]):
    html_str = ''
    if names:
        html_str += ('<tr>' + 
                     ''.join(f'<td style="text-align:center">{name}</td>' for name in names) + 
                     '</tr>')
    html_str += ('<tr>' + 
                 ''.join(f'<td style="vertical-align:top"> {df.to_html(index=False)}</td>' 
                         for df in dfs) + 
                 '</tr>')
    html_str = f'<table>{html_str}</table>'
    html_str = html_str.replace('table','table style="display:inline"')
    display_html(html_str, raw=True)

여기에 이미지 설명 입력


gibbone (스타일 및 캡션 설정)과 stevi (공간 추가)의 접근 방식을 결합하여 판다 데이터 프레임을 테이블로 나란히 출력하는 함수 버전을 만들었습니다.

from IPython.core.display import display, HTML

def display_side_by_side(dfs:list, captions:list):
    """Display tables side by side to save vertical space
    Input:
        dfs: list of pandas.DataFrame
        captions: list of table captions
    """
    output = ""
    combined = dict(zip(captions, dfs))
    for caption, df in combined.items():
        output += df.style.set_table_attributes("style='display:inline'").set_caption(caption)._repr_html_()
        output += "\xa0\xa0\xa0"
    display(HTML(output))

용법 :

display_side_by_side([df1, df2, df3], ['caption1', 'caption2', 'caption3'])

다수 :

여기에 이미지 설명 입력


Gibbone의 답변이 저에게 딱 맞습니다! 테이블 사이에 추가 공간을 원하면 제안한 코드로 이동 "\xa0\xa0\xa0"하여 다음 코드 줄에 추가하십시오 .

display_html(df1_styler._repr_html_()+"\xa0\xa0\xa0"+df2_styler._repr_html_(), raw=True)

HBOX를 사용하게되었습니다.

import ipywidgets as ipyw

def get_html_table(target_df, title):
    df_style = target_df.style.set_table_attributes("style='border:2px solid;font-size:10px;margin:10px'").set_caption(title)
    return df_style._repr_html_()

df_2_html_table = get_html_table(df_2, 'Data from Google Sheet')
df_4_html_table = get_html_table(df_4, 'Data from Jira')
ipyw.HBox((ipyw.HTML(df_2_html_table),ipyw.HTML(df_4_html_table)))

참고 URL : https://stackoverflow.com/questions/38783027/jupyter-notebook-display-two-pandas-tables-side-by-side

반응형