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

如何将DataFrame列标题转换为行?df.transpose()后列标题变为0、1、2的问题排查与解决

Fixing Column Names After Pandas DataFrame Transpose

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 years199019911992
Angola847180
Botswana655962

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:

  1. Set the country column as the DataFrame index
    First, we need to tell Pandas that the Calendar years column contains our row labels (country names) instead of regular data. This ensures those names get carried over during transpose.

  2. Transpose the DataFrame
    Now when you transpose, the country names will become the new column headers, and the years will become the row index.

  3. Clean up the index to make it a proper column
    Finally, convert the year-based row index into a dedicated Calendar years column 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 yearsAngolaBotswanaCameroon
1990846572
1991715968
1992806270

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 16:29:10