To add lines between cells or apply different coloring to specific cells in Python, especially within Jupyter Notebooks, you can use pandas' Styler or HTML/CSS with libraries like tabulate or ipytable. Below are methods to achieve this:
1. Using Pandas Styler (for Jupyter Notebooks)
Pandas' Styler allows you to style DataFrames with borders, background colors, and more.
Add Borders Between Cells
python
import pandas as pd
df = pd.DataFrame({
'A': [1, 2, 3],
'B': [4, 5, 6]
})
# Add borders to all cells
styled_df = df.style.set_properties(**{'border': '1px solid black'})
# Display the styled DataFrame
styled_df
Color Specific Cells
python
# Highlight cells with values > 5
def highlight_cells(x):
return ['background-color: yellow' if val > 5 else '' for val in x]
styled_df = df.style.apply(highlight_cells, axis=1)
styled_df
Conditional Coloring Based on Columns
python
# Color cells in column 'A' with red background
def color_column_A(x):
return ['background-color: red' if col == 'A' else '' for col in x.index]
styled_df = df.style.apply(color_column_A, axis=1)
styled_df
2. Using HTML/CSS with tabulate
If you want to generate HTML tables with custom styling, use the tabulate library:
python
from tabulate import tabulate
data = [
[1, 4],
[2, 5],
[3, 6]
]
# Generate HTML with custom CSS
html_table = tabulate(data, headers="keys", tablefmt="html")
# Add CSS for borders and colors
css = """
<style>
table {
border-collapse: collapse;
width: 50%;
}
th, td {
border: 1px solid black;
padding: 8px;
text-align: center;
}
.highlight {
background-color: yellow;
}
</style>
"""
# Combine CSS and HTML
final_html = css + html_table
display(final_html)
3. Using ipytable (Interactive Tables)
If you're using the ipytable Jupyter widget, you can style cells with custom CSS:
python
from ipytable import Table
data = [[1, 2], [3, 4]]
table = Table(data)
# Add CSS for borders and colors
table.css = """
td {
border: 1px solid black;
padding: 5px;
}
td:nth-child(2) {
background-color: lightblue;
}
"""
table
4. Custom CSS for HTML Output
If you're generating HTML tables manually, inject CSS directly: