You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何截取Pandas DataFrame首尾?用tabulate展示首尾5行数据

Hey there! Let's break down your two questions about Pandas and tabulate:

1. How to slice the start and end of a Pandas DataFrame?

Pandas makes this super straightforward with two built-in methods:

  • head(n): Grabs the first n rows of your DataFrame. If you don't specify n, it defaults to 5. For example, df.head(10) gives you the first 10 rows.
  • tail(n): Fetches the last n rows, also defaulting to 5 if n isn't provided. df.tail(10) gets you the final 10 rows.

If you want to combine both the start and end sections into a single DataFrame, just use pd.concat() to stitch them together:

import pandas as pd

# Example 100-row DataFrame
df = pd.DataFrame({'ColumnA': range(100), 'ColumnB': range(100, 200)})

# Combine first 5 and last 5 rows
trimmed_df = pd.concat([df.head(5), df.tail(5)], ignore_index=True)
print(trimmed_df)
2. Printing a truncated table with tabulate (first 5, ellipsis, last 5)

To get that clean truncated table with an ellipsis in the middle, we can build a custom DataFrame that includes your top rows, a row of ellipses, and your bottom rows, then pass that to tabulate. Here's how:

import pandas as pd
from tabulate import tabulate

# Your original 100-row DataFrame (replace with your actual data)
df = pd.DataFrame({
    'Col1': range(100),
    'Col2': [x*2 for x in range(100)],
    'Col3': [x+50 for x in range(100)]
})

# Grab the top 5 and bottom 5 rows
top_rows = df.head(5)
bottom_rows = df.tail(5)

# Create a row of ellipses that matches your DataFrame's columns
ellipsis_row = pd.DataFrame([['...'] * len(df.columns)], columns=df.columns)

# Combine all three parts
display_df = pd.concat([top_rows, ellipsis_row, bottom_rows], ignore_index=True)

# Print with tabulate using your preferred format
print(tabulate(display_df, headers='keys', tablefmt='psql'))

This will output a nice psql-style table that looks like this:

+----+-------+-------+-------+
|    | Col1  | Col2  | Col3  |
|----+-------+-------+-------|
|  0 | 0     | 0     | 50    |
|  1 | 1     | 2     | 51    |
|  2 | 2     | 4     | 52    |
|  3 | 3     | 6     | 53    |
|  4 | 4     | 8     | 54    |
|  5 | ...   | ...   | ...   |
|  6 | 95    | 190   | 145   |
|  7 | 96    | 192   | 146   |
|  8 | 97    | 194   | 147   |
|  9 | 98    | 196   | 148   |
| 10 | 99    | 198   | 149   |
+----+-------+-------+-------+

The key here is making sure the ellipsis row uses the exact same column names as your original DataFrame—this ensures tabulate renders the table correctly with matching headers.

内容的提问来源于stack exchange,提问作者ferengi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:18:22