pandas - tutorial - python jupyter game
ジュピターのノートブックは、2つの Pandas テーブルを並べて表示 (4)
@ 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)
私は2つのパンダのデータフレームを持っており、Jupyterのノートブックにそれらを表示したいと思います。
次のようなことをする:
display(df1)
display(df2)
それらを次々と表示します:
私は、最初のデータフレームの右側に2番目のデータフレームを持っていたいと思います。 同様の質問がありますが、そこには人が1つのデータフレームでそれらの違いを示すことをマージすることで満足しているようです。
これは私のためには機能しません。 私の場合、データフレームは完全に異なる(類似しない要素を表す)ことができ、それらのサイズは異なる可能性があります。 したがって、私の主な目標はスペースを節約することです。
pandas 0.17.1
から、データpandas 0.17.1
の視覚化をパンダのスタイリング方法で直接変更することができます
2つのDataFramesを並べて"style='display:inline'"
は、 ntg answerで提案されているように、引数"style='display:inline'"
set_table_attributes
を使用する必要があります。 2つのStyler
オブジェクトが返されます。アライメントされたデータフレームを表示するには、IPythonのdisplay_html
メソッドを使用して、結合された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('Table 1')
df2_styler = df2.style.set_table_attributes("style='display:inline'").set_caption('Table 2')
display_html(df1_styler._repr_html_()+df2_styler._repr_html_(), raw=True)
この方法では、他のスタイリングオプションも簡単に追加できます。 ここで要求されたように、キャプションを追加する方法は次のとおりhere 。
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)
出力コードの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))
もちろん、CSSをさらにカスタマイズすることもできます。
1つのセルの出力のみをターゲットにする場合は、 :nth-child()
セレクタを使用してみてください。 たとえば、このコードでは、ノートブックの5番目のセルのみの出力のCSSが変更されます。
CSS = """
div.cell:nth-child(5) .output {
flex-direction: row;
}
"""
私のソリューションは、HTMLで表を構築し、CSSのハックを生成せずに出力します。
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)