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

如何用Pandas将DataFrame指定列转为行?保留time列作为索引

Reshape Wide Dataframe to Long Format (Transpose Columns to Rows)

Got it, let's fix this for you! What you're trying to do is reshape your wide dataframe into a long (tidy) format—this is a super common task, and you were already on the right track with melt! The issue was just a tiny parameter mix-up.

Let's Break Down the Solution

First, let's recap your goal:

  • Keep the time column as your identifier (each row in the original data should map to multiple rows in the output, one for each colA-colG).
  • Turn the column names colA-colG into values in a new cols column.
  • Turn the values under colA-colG into values in a new vals column.

Correct Usage of pd.melt()

Your earlier melt attempt failed because you used id_vars='time_period'—but your original data's identifier column is named time, not time_period. Here's the fix:

Step 1: Create Example Data (to replicate your scenario)

import pandas as pd

# Your sample data
data = {
    'time': [12, 13],
    'colA': [1, 2],
    'colB': [4, 7],
    'colC': [5, 6],
    'colD': [9, 8],
    'colE': [4, 3],
    'colF': [3, 4],
    'colG': [3, 5]
}
df = pd.DataFrame(data)

Step 2: Reshape with melt

# This will give you exactly the output you want
long_df = df.melt(
    id_vars='time',       # Column to keep as identifier
    var_name='cols',      # Name for the new column holding original column names
    value_name='vals'     # Name for the new column holding the values
)

Step 3: Result

Running the code above will produce this output:

time cols  vals
0    12 colA     1
1    13 colA     2
2    12 colB     4
3    13 colB     7
4    12 colC     5
5    13 colC     6
6    12 colD     9
7    13 colD     8
8    12 colE     4
9    13 colE     3
10   12 colF     3
11   13 colF     4
12   12 colG     3
13   13 colG     5

Why Your Previous Attempts Didn't Work

  • df.transpose(): This just flips the entire table (rows ↔ columns), which turns your time values into row labels and original rows into column names—totally not what you need for this task.
  • Pivot tables: pivot() or pivot_table() are used to convert long data to wide data, which is the opposite of your goal, so they aren't the right tool here.
  • Your original melt call: The typo in id_vars (using time_period instead of time) was the only issue—fix that and it works perfectly!

Extra: Be Explicit with Columns (Optional)

If your dataframe has other columns you don't want to include in the reshaping, you can explicitly list the columns to unpivot using value_vars:

long_df = df.melt(
    id_vars='time',
    value_vars=['colA', 'colB', 'colC', 'colD', 'colE', 'colF', 'colG'],
    var_name='cols',
    value_name='vals'
)

This ensures you only reshape the columns you intend to, avoiding any unexpected data in your output.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:18:31