在R语言中重塑数据框结构:长格式转宽格式的简便方法咨询
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

