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

在R语言中重塑数据框结构:长格式转宽格式的简便方法咨询

Reshape DataFrame from Long to Wide Format in Pandas

Absolutely! This is a common data reshaping task, and pandas has a straightforward solution using the pivot() method. Here's how you can do it:

Step 1: Start with your original DataFrame

First, let's assume you have your data loaded into a pandas DataFrame (if not, you can create it like this):

import pandas as pd

data = {
    'Dependant var': ['Vd1', 'Vd1', 'Vd1', 'Vd1', 'Vd2', 'Vd2', 'Vd2', 'Vd2'],
    'independant var': ['Vi1', 'Vi2', 'Vi3', 'Vi4', 'Vi1', 'Vi2', 'Vi3', 'Vi4'],
    'p-value': [0.0345, 0.0025, 0.0005, 0.0305, 0.0800, 0.0000, 0.0005, 0.0004]
}

df = pd.DataFrame(data)

Step 2: Use pivot() to reshape to wide format

The pivot() method lets you specify which column becomes the index, which becomes the columns, and which holds the values:

# Reshape the DataFrame
wide_df = df.pivot(
    index='Dependant var',
    columns='independant var',
    values='p-value'
).reset_index()

# Optional: Remove the extra header name for the independent variables
wide_df.columns.name = None

Result

This will give you exactly the structure you want:

Dependant var    Vi1    Vi2    Vi3    Vi4
0            Vd1  0.0345 0.0025 0.0005 0.0305
1            Vd2  0.0800 0.0000 0.0005 0.0004

Note

If you ever have duplicate entries for the same combination of Dependant var and independant var, use pivot_table() instead (with an aggregation function like mean or sum to handle duplicates). But since your data has unique pairs, pivot() is the simplest and most efficient choice.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 14:17:45