如何截取Pandas DataFrame首尾?用tabulate展示首尾5行数据
Hey there! Let's break down your two questions about Pandas and tabulate:
Pandas makes this super straightforward with two built-in methods:
head(n): Grabs the firstnrows of your DataFrame. If you don't specifyn, it defaults to 5. For example,df.head(10)gives you the first 10 rows.tail(n): Fetches the lastnrows, also defaulting to 5 ifnisn'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)
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

