如何将DataFrame列标题转换为行?df.transpose()后列标题变为0、1、2的问题排查与解决
I get it, transposing your DataFrame and ending up with column names like 0, 1, 2 instead of the country names (like Angola) is super frustrating. Let's break down why this happens and how to fix it properly.
Why the Default Transpose Fails
Your original DataFrame structure looks something like this:
| Calendar years | 1990 | 1991 | 1992 |
|---|---|---|---|
| Angola | 84 | 71 | 80 |
| Botswana | 65 | 59 | 62 |
When you run df.transpose() directly, Pandas uses the default numeric row indexes (0, 1, 2...) as the new column names. What you actually want is the values from the Calendar years column (the country names) to become your new columns.
Step-by-Step Solution
Here's how to fix this in a few simple steps:
Set the country column as the DataFrame index
First, we need to tell Pandas that theCalendar yearscolumn contains our row labels (country names) instead of regular data. This ensures those names get carried over during transpose.Transpose the DataFrame
Now when you transpose, the country names will become the new column headers, and the years will become the row index.Clean up the index to make it a proper column
Finally, convert the year-based row index into a dedicatedCalendar yearscolumn to match your desired output.
Full Code Example
import pandas as pd # Simulate your original dataset original_data = { "Calendar years": ["Angola", "Botswana", "Cameroon"], "1990": [84, 65, 72], "1991": [71, 59, 68], "1992": [80, 62, 70] } df = pd.DataFrame(original_data) # Fix the transpose issue transposed_df = ( df .set_index("Calendar years") # Use country names as row index .transpose() # Flip rows and columns .reset_index() # Turn year index into a column .rename(columns={"index": "Calendar years"}) # Rename to match your desired header ) print(transposed_df)
Output You'll Get
This will give you exactly the structure you want:
| Calendar years | Angola | Botswana | Cameroon |
|---|---|---|---|
| 1990 | 84 | 65 | 72 |
| 1991 | 71 | 59 | 68 |
| 1992 | 80 | 62 | 70 |
Quick Chain Version
If you prefer concise code, you can combine all steps into one line without losing readability:
transposed_df = df.set_index("Calendar years").transpose().reset_index().rename(columns={"index": "Calendar years"})
That's it! This approach ensures your column names stay meaningful instead of turning into a random numeric sequence.
内容的提问来源于stack exchange,提问作者wamika

