programing

iPython 노트북에서 DataFrame을 표로 표시

lovejava 2023. 9. 6. 21:40

iPython 노트북에서 DataFrame을 표로 표시

저는 iPython 노트북을 사용하고 있습니다.이 작업을 수행할 때:

df

나는 세포가 있는 아름다운 테이블을 얻습니다.그러나 이렇게 하면 다음과 같습니다.

df1
df2 

첫번째 아름다운 테이블을 인쇄하지 않습니다.시도해보면 다음과 같습니다.

print df1
print df2

테이블을 다른 형식으로 출력하기 때문에 열이 넘쳐 출력이 매우 높아집니다.

두 데이터셋 모두에 대해 아름다운 표를 강제로 출력할 수 있는 방법이 있습니까?

사용해야 할 것입니다.HTML()아니면display()IPython의 디스플레이 모듈의 기능:

from IPython.display import display, HTML

# Assuming that dataframes df1 and df2 are already defined:
print "Dataframe 1:"
display(df1)
print "Dataframe 2:"
display(HTML(df2.to_html()))

만약 당신이 그냥print df1.to_html()미입력 HTML을 받으실 수 있습니다.

다음에서 가져올 수도 있습니다.IPython.core.display같은 효과로

from IPython.display import display
display(df)  # OR
print df.to_html()

이 답은 이 블로그 포스트의 두 번째 팁에 근거한 것입니다: 28 Jupyter 노트북 팁, 요령과 단축키

노트북 상단에 다음 코드를 추가할 수 있습니다.

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

이것은 Jupyter에게 변수나 문장에 대한 결과를 자신의 라인에 인쇄하도록 지시합니다.그러면 당신은 그 다음에 오직 그 다음을 포함하는 셀을 실행할 수 있습니다.

df1
df2

그리고 "두 데이터셋 모두에 대한 아름다운 표를 출력"할 것입니다.

저는 HTML을 가지고 장난치지 않고 최대한 네이티브 인프라를 사용하는 것을 선호합니다.출력 위젯을 Hbox 또는 Vbox와 함께 사용할 수 있습니다.

import ipywidgets as widgets
from IPython import display
import pandas as pd
import numpy as np

# sample data
df1 = pd.DataFrame(np.random.randn(8, 3))
df2 = pd.DataFrame(np.random.randn(8, 3))

# create output widgets
widget1 = widgets.Output()
widget2 = widgets.Output()

# render in output widgets
with widget1:
    display.display(df1)
with widget2:
    display.display(df2)

# create HBox
hbox = widgets.HBox([widget1, widget2])

# render hbox
hbox

출력은 다음과 같이 출력합니다.

enter image description here

주피터 노트북에서 DataFrame을 표시하려면 다음을 입력하면 됩니다.

display(이름_of_the_DataFrame)

예를 들어 다음과 같습니다.

표시(df)

디스플레이에 쉼표를 사용해서 두 dfs를 모두 표시하면 될 것 같습니다.깃허브에 있는 몇몇 노트에서 이것을 발견했습니다.이 코드는 제이크 밴더플라스의 공책에서 나온 것입니다.

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)

display('df', "df2")

마크다운을 사용하여 테이블을 만들 수 있습니다.설치하라는 메시지가 표시됩니다.tabulate아직 이용할 수 없는 경우 먼저 패키지를 제공합니다.

from IPython.display import display, Markdown

display(Markdown(df.to_markdown()))

목록에 포함된 데이터 프레임을 표시하려면:

dfs = [df1, df2]
display(*dfs)

다른 대답으로는,

옵션을 사용하려면 context manager를 사용하면 됩니다.

from IPython.display import display

with pd.option_context('precision', 3):
    display(df1)
    display(df2)

언급URL : https://stackoverflow.com/questions/26873127/show-dataframe-as-table-in-ipython-notebook