Keywords: Jupyter Notebook | Pandas | CSS Layout | Data Visualization | IPython.display
Abstract: This article provides an in-depth exploration of techniques for displaying multiple Pandas DataFrames side by side in Jupyter Notebook, with a focus on CSS flex layout methods. Through detailed analysis of the integration between IPython.display module and CSS style control, it offers complete code implementations and theoretical explanations, while comparing the advantages and disadvantages of alternative approaches. Starting from practical problems, the article systematically explains how to achieve horizontal arrangement by modifying the flex-direction property of output containers, extending to more complex styling scenarios.
Problem Context and Requirements Analysis
In data science workflows, Jupyter Notebook as an interactive development environment frequently requires simultaneous display of multiple Pandas DataFrames for comparative analysis. However, the default display method stacks DataFrames vertically, which proves inefficient when comparing different data sources or conserving screen space. Users typically face two core requirements: maintaining DataFrame independence (avoiding merging into a single DataFrame) and achieving flexible spatial layout.
Core Solution: CSS Flex Layout Control
Based on the integration between IPython.display module and CSS style control, we can achieve horizontal arrangement by modifying the flex-direction property of output containers. Here is the complete implementation code:
import pandas as pd
import numpy as np
from IPython.display import display, HTML
CSS = """
.output {
flex-direction: row;
}
"""
HTML('<style>{}</style>'.format(CSS))
This code works by injecting custom CSS styles through the HTML function, changing the flex-direction property of the .output class from the default column to row. In Jupyter Notebook's rendering mechanism, each output cell contains the .output class, and this modification globally affects all subsequent outputs.
Technical Principles Deep Dive
Jupyter Notebook uses the flexbox layout model to manage output content. The flex-direction property defines the main axis direction:
flex-direction: column(default): Vertical arrangement, child elements stack from top to bottomflex-direction: row: Horizontal arrangement, child elements align from left to right
When multiple display() calls execute within the same cell, each DataFrame's HTML output becomes a child element of the .output container. By modifying flex-direction, we change the arrangement direction of these child elements.
Advanced Applications and Customization
1. Precise Control of Specific Cells
To avoid global style effects, CSS selectors can precisely control specific cells:
CSS = """
div.cell:nth-child(5) .output {
flex-direction: row;
}
"""
This selector only affects the output of the 5th cell. The nth-child selector provides flexible positioning capabilities, allowing index adjustment based on specific needs.
2. Responsive Layout Optimization
Combining with the flex-wrap property enables smarter layouts:
CSS = """
.output {
flex-direction: row;
flex-wrap: wrap;
justify-content: space-between;
}
"""
This configuration allows DataFrames to wrap automatically when space is insufficient and achieves even distribution through space-between.
Alternative Solutions Comparative Analysis
Solution 1: Custom HTML Concatenation Function
Based on Answer 1's implementation, manually concatenating HTML with display:inline styling:
from IPython.display import display_html
from itertools import chain,cycle
def display_side_by_side(*args, titles=cycle([''])):
html_str = ''
for df, title in zip(args, chain(titles, cycle(['</br>']))):
html_str += '<th style="text-align:center"><td style="vertical-align:top">'
html_str += f'<h2 style="text-align: center;">{title}</h2>'
html_str += df.to_html().replace('table', 'table style="display:inline"')
html_str += '</td></th>'
display_html(html_str, raw=True)
This method provides title support but requires manual HTML structure management with lower flexibility.
Solution 2: Pandas Styler API
Based on Answer 3's implementation, using pandas 0.17.1+ styling features:
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)
This method integrates deeply with pandas, supporting rich styling options, but requires newer pandas versions.
Performance and Compatibility Considerations
The CSS flex layout method offers these advantages:
- High Performance: Native browser support for flex layout ensures excellent rendering performance
- Good Compatibility: Modern browsers including Chrome, Firefox, Safari support flexbox
- Easy Maintenance: Only requires CSS property modifications without complex HTML operations
- Strong Extensibility: Easy to add other flex properties for fine-tuning
Practical Application Example
Here is a complete working example demonstrating how to use this method in actual projects:
# Create sample DataFrames
df1 = pd.DataFrame(np.random.randn(3, 4), columns=['A', 'B', 'C', 'D'])
df2 = pd.DataFrame(np.random.randn(4, 3), columns=['X', 'Y', 'Z'])
# Apply CSS styles
CSS = """
.output {
flex-direction: row;
gap: 20px;
}
"""
HTML('<style>{}</style>'.format(CSS))
# Display DataFrames
print("DataFrame 1:")
display(df1)
print("\nDataFrame 2:")
display(df2)
This example shows how to handle differently shaped DataFrames and add spacing through the gap property.
Best Practice Recommendations
- Style Isolation: Place CSS style definitions in separate code cells for easier management and debugging
- Version Control: Document pandas and IPython versions used to ensure code reproducibility
- Progressive Enhancement: Implement basic functionality first, then gradually add advanced features
- Documentation Comments: Add clear comments in code explaining the purpose and effects of style modifications
Conclusion
Implementing side-by-side display of Pandas DataFrames through CSS flex layout control represents a concise, efficient, and maintainable technical solution. This method fully utilizes modern browsers' layout capabilities, avoids complex HTML operations, and maintains good extensibility. In practical applications, different implementation strategies can be selected based on specific requirements, balancing functional needs with code complexity.