How to Display DataFrame in pandas: Syntax and Examples
To display a DataFrame in pandas, simply type the DataFrame variable name in a Jupyter notebook or use
print() in scripts. You can also use df.head() to show the first few rows or df.tail() for the last rows.Syntax
To display a DataFrame, you can use the following methods:
print(df): Prints the entire DataFrame in the console.df: In interactive environments like Jupyter, typing the variable name shows a formatted table.df.head(n): Shows the firstnrows (default 5).df.tail(n): Shows the lastnrows (default 5).
python
print(df)
df
df.head()
df.tail()Example
This example creates a simple DataFrame and shows how to display it using different methods.
python
import pandas as pd data = {'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva'], 'Age': [25, 30, 35, 40, 45], 'City': ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix']} df = pd.DataFrame(data) print("Using print():") print(df) print("\nUsing df.head():") print(df.head(3)) print("\nUsing df.tail():") print(df.tail(2))
Output
Using print():
Name Age City
0 Alice 25 New York
1 Bob 30 Los Angeles
2 Charlie 35 Chicago
3 David 40 Houston
4 Eva 45 Phoenix
Using df.head():
Name Age City
0 Alice 25 New York
1 Bob 30 Los Angeles
2 Charlie 35 Chicago
Using df.tail():
Name Age City
3 David 40 Houston
4 Eva 45 Phoenix
Common Pitfalls
Some common mistakes when displaying DataFrames include:
- Using
print(df)in Jupyter notebooks instead of just typingdffor a nicer table view. - Trying to display very large DataFrames fully, which can flood the console.
- Not using
head()ortail()to preview data when the DataFrame is large.
Always preview data with df.head() to avoid overwhelming output.
python
import pandas as pd data = {'A': range(1000)} df = pd.DataFrame(data) # Wrong: printing entire large DataFrame #print(df) # This floods the console # Right: preview first 5 rows print(df.head())
Output
A
0 0
1 1
2 2
3 3
4 4
Quick Reference
| Method | Description |
|---|---|
| print(df) | Prints the entire DataFrame in console |
| df | Displays DataFrame in Jupyter with formatting |
| df.head(n) | Shows first n rows (default 5) |
| df.tail(n) | Shows last n rows (default 5) |
Key Takeaways
Use
print(df) or just df in Jupyter to display DataFrames.Use
df.head() or df.tail() to preview parts of large DataFrames.Avoid printing very large DataFrames fully to prevent flooding the console.
Typing the DataFrame variable in Jupyter shows a clean, formatted table automatically.