# Pandas Tables: formatear DataFrames como tablas

Un DataFrame de la [Biblioteca Python Pandas](https://www.ionos.com/es-us/digitalguide/paginas-web/desarrollo-web/python-pandas/) puede utilizarse para **presentar datos en forma de tabla**. Existen varias opciones para mostrar conjuntos de datos de manera estructurada y clara en forma de Pandas Tables o tablas en Pandas. \[TOC\]

## Visualización estándar de un DataFrame de Pandas como tabla

La **forma más fácil** de mostrar un [DataFrame de Pandas](https://www.ionos.com/es-us/digitalguide/paginas-web/desarrollo-web/dataframes-de-pandas-python/) como tabla es mediante la [función print de Python](https://www.ionos.com/es-us/digitalguide/paginas-web/desarrollo-web/python-print/). Esta te devuelve una representación en forma de tabla del DataFrame:

```python
import pandas as pd
# Crear un DataFrame de ejemplo
data = {
    'Nombre': ['Anna', 'Zoe', 'Charlie', 'Daniela'],
    'Edad': [23, 30, 35, 29],
    'Profesión': ['Ingeniera', 'Maestra', 'Médico', 'Diseñadora']
}
df = pd.DataFrame(data)
# Mostrar el DataFrame como tabla
print(df)
```

El DataFrame de Pandas se muestra como una tabla simple en la consola. La salida de la tabla se ve de la siguiente manera:

```none
Nombre   Edad    Profesión
0     Anna     23    Ingeniera
1      Zoe     30      Maestra
2     Charlie     35       Médico
3     Daniela     29      Diseñadora
```

Nota Si usas **[Jupyter Notebook](https://www.ionos.com/es-us/digitalguide/paginas-web/desarrollo-web/jupyter-notebook/)** no necesitas ni siquiera la función `print()` para mostrar tu DataFrame de Pandas en forma de tabla. Una **simple llamada** al DataFrame es suficiente para que se presente en formato tabular.

## Visualización con `to_string()` para un control completo

La función integrada de Pandas `DataFrame.to_string()` convierte un **DataFrame en una [string de Python](https://www.ionos.com/es-us/digitalguide/paginas-web/desarrollo-web/python-string/)**. Permite mostrar el DataFrame completo como una tabla, incluso si es muy grande. A continuación, se utiliza el mismo DataFrame que en el primer ejemplo:

```python
# Mostrar el DataFrame completo como tabla
print(df.to_string())
```

El resultado sería el siguiente:

```none
Nombre   Edad      Profesión
0     Anna     23      Ingeniera
1      Zoe     30     Maestra
2     Charlie     35      Médico
3     Daniela     29     Diseñadora
```

## Cómo utilizar `style` para formatear la tabla

Pandas también ofrece una forma integrada de resaltar y formatear DataFrames: la propiedad `style`. En el siguiente código, se resaltarán los valores máximos del conjunto de datos de nuestro ejemplo:

```python
# Mostrar DataFrame con valores máximos resaltados
df.style.highlight_max(axis=0)
```

En un Jupyter Notebook, el DataFrame se mostrará con los valores máximos resaltados en color.

### Uso de `to_html()` para frameworks web

Con `DataFrame.to_html()` puedes mostrar tu DataFrame como una [tabla HTML](https://www.ionos.com/es-us/digitalguide/paginas-web/desarrollo-web/tablas-en-html/) con una sola llamada a la función, lo que permite integrarlo directamente en aplicaciones web. Para hacerlo, simplemente debes llamar a la función en el DataFrame:

```python
# Mostrar DataFrame como tabla HTML
html_table = df.to_html()
print(html_table)
```

Como resultado, obtendrás código HTML. Este código se puede incrustar en páginas web.

```html
<table border="1" class="dataframe">
    <thead>
        <tr style="text-align: right;">
            <th></th>
            <th>Nombre</th>
            <th>Edad</th>
            <th>Profesión</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>0</th>
            <td>Anna</td>
            <td>23</td>
            <td>Ingeniera</td>
        </tr>
        <tr>
            <th>1</th>
            <td>Zoe</td>
            <td>30</td>
            <td>Maestra</td>
        </tr>
        <tr>
            <th>2</th>
            <td>Charlie</td>
            <td>35</td>
            <td>Médico</td>
        </tr>
        <tr>
            <th>3</th>
            <td>Daniela</td>
            <td>29</td>
            <td>Diseñadora</td>
        </tr>
    </tbody>
</table>
```

Nota De manera similar a `to_html()`, la función de Pandas `DataFrame.to_markdown()` genera una tabla en formato **[Markdown](https://www.ionos.com/es-us/digitalguide/paginas-web/desarrollo-web/tutorial-de-markdown/) en lugar de HTML**. Este formato es ampliamente utilizado en muchas herramientas de documentación o blogs.

## Uso de `tabulate` para diferentes formatos de tabla

Con el módulo externo de Python `tabulate`, se pueden mostrar DataFrames de Pandas en varios formatos tabulares. Se admiten, entre otros, formatos como GitHub Flavored Markdown, reStructuredText o texto plano. El formato deseado se especifica simplemente pasando el parámetro `tablefmt`. A continuación, te mostramos el DataFrame en formato Markdown de GitHub:

```python
from tabulate import tabulate
# Mostrar el DataFrame como tabla en formato Markdown
print(tabulate(df, headers='keys', tablefmt='github'))
```

Se produce el siguiente resultado:

```none
|  | Nombre | Edad | Profesión |
| --- | --- | --- | --- |
| 0 | Anna | 23 | Ingeniera |
| 1 | Zoe | 30 | Maestra |
| 2 | Charlie | 35 | Médico |
| 3 | Daniela | 29 | Diseñadora |
```


This is a markdown version of: [https://www.ionos.com/es-us/digitalguide/paginas-web/desarrollo-web/dataframe-de-pandas-python-en-tabla/](https://www.ionos.com/es-us/digitalguide/paginas-web/desarrollo-web/dataframe-de-pandas-python-en-tabla/) for AI/LLM consumption.