Mostrar DataFrame como tabla en el cuaderno IPython


Estoy usando IPython notebook. Cuando hago esto:

df

Obtengo una hermosa mesa con celdas. Sin embargo, si hago esto:

df1
df2 

No imprime la primera tabla hermosa. Si intento esto:

print df1
print df2

Imprime la tabla en un formato diferente que derrama columnas y hace que la salida sea muy alta.

¿Hay alguna manera de forzarlo a imprimir las hermosas tablas para ambos conjuntos de datos?

Author: smci, 2014-11-11

4 answers

Necesitará usar las funciones HTML() o display() del módulo de visualización de 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()))

Tenga en cuenta que si solo print df1.to_html() obtendrá el HTML sin procesar.

También puede importar desde IPython.core.display con el mismo efecto

 221
Author: emunsing,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-08 01:39:51

Publicando el comentario de @joris como respuesta:

Display(df) (con from IPython.display import display), o imprimir df.to_html ()


O en código:

from IPython.display import display
display(df)  # OR
print df.to_html()
 29
Author: JacobWuzHere,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-26 01:38:00

Esta respuesta se basa en el segundo consejo de esta entrada del blog: 28 Consejos, trucos y atajos de Jupyter Notebook

Puede agregar el siguiente código a la parte superior de su cuaderno

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

Esto le dice a Jupyter que imprima los resultados de cualquier variable o sentencia en su propia línea. Por lo tanto, puede ejecutar una celda que contenga únicamente

df1
df2

Y "imprimirá las hermosas tablas para ambos conjuntos de datos".

 21
Author: Jonny Brooks,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-11 14:30:53

Parece que puede mostrar ambos dfs usando una coma intermedia en la pantalla. Me di cuenta de esto en algunos cuadernos en Github. Este código es del cuaderno de Jake VanderPlas.

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")

 3
Author: Moondra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-14 23:04:13