如何在Pandas中同时显示列索引与列名?
Great question! It’s totally reasonable to want a built-in Pandas solution instead of writing a custom function for this. Let’s break down why your initial df.info(verbose=True) attempt didn’t work, then cover the built-in alternatives you’re looking for.
Why df.info(verbose=True) doesn’t show column indices
The verbose parameter in df.info() controls whether to display full details for all columns (when you have a large DataFrame with more than the default max_cols limit). It doesn’t add column index positions to the output—this isn’t a feature of df.info() at all, so that’s why you saw identical results with or without it.
Built-in Pandas methods to show column indices + names
Here are a few clean, built-in ways to get exactly what you want:
1. Use df.columns.to_string() for a simple printed output
This is the quickest way to print indices alongside column names in a readable format:
import pandas as pd records = {'a':['abc','def','ghi'], 'b':[22,41,13], 'c':[133,3123,552]} df = pd.DataFrame(records) print(df.columns.to_string())
Output:
0 a 1 b 2 c
2. Convert columns to a DataFrame for structured output
If you want a tabular format (which you can further manipulate or save), use df.columns.to_frame():
df.columns.to_frame(name='Column Name')
This returns a DataFrame where the index is the column position, and the single column holds the names:
| Column Name | |
|---|---|
| 0 | a |
| 1 | b |
| 2 | c |
3. Create a custom DataFrame for explicit labeling
For even clearer labeling, you can wrap the column index and names into a new DataFrame explicitly:
pd.DataFrame({'Column Index': df.columns.index, 'Column Name': df.columns})
Output:
| Column Index | Column Name | |
|---|---|---|
| 0 | 0 | a |
| 1 | 1 | b |
| 2 | 2 | c |
All of these methods are built into Pandas, so you don’t need to maintain a custom function. The first option is best for quick printing, while the latter two give you structured data to work with if needed.
内容的提问来源于stack exchange,提问作者callmeanythingyouwant

