如何用Pandas将DataFrame指定列转为行?保留time列作为索引
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
timecolumn as your identifier (each row in the original data should map to multiple rows in the output, one for eachcolA-colG). - Turn the column names
colA-colGinto values in a newcolscolumn. - Turn the values under
colA-colGinto values in a newvalscolumn.
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 yourtimevalues into row labels and original rows into column names—totally not what you need for this task.- Pivot tables:
pivot()orpivot_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
meltcall: The typo inid_vars(usingtime_periodinstead oftime) 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

