如何将DataFrame行数据转换为不同列?已尝试Pivot Table未成功
Solution to Reshape Your Data
Using Python Pandas
You can easily reshape the data using pandas to match your desired format. Here's the step-by-step code:
import pandas as pd # Load your original data data = [ [1, 10, 210, 220], [2, 10, 245, 255], [3, 10, 275, 285], [4, 10, 295, 305], [1, 20, 215, 225], [2, 20, 250, 260], [3, 20, 280, 290], [4, 20, 300, 310] ] df = pd.DataFrame(data, columns=['depth', 'density', 'tb10', 'tb18']) # Reshape by unstacking density values df.set_index(['depth', 'density'], inplace=True) df_unstacked = df.unstack(level='density') # Flatten multi-level column names df_unstacked.columns = [f'den{density}_{tb_col}' for tb_col, density in df_unstacked.columns] # Reset index and add density column (as per your desired output) result = df_unstacked.reset_index() result['density'] = 10 # Reorder columns to match your target format result = result[['depth', 'density', 'den10_tb10', 'den10_tb18', 'den20_tb10', 'den20_tb18']] # Output as markdown table print(result.to_markdown(index=False))
Output:
| depth | density | den10_tb10 | den10_tb18 | den20_tb10 | den20_tb18 |
|---|---|---|---|---|---|
| 1 | 10 | 210 | 220 | 215 | 225 |
| 2 | 10 | 245 | 255 | 250 | 260 |
| 3 | 10 | 275 | 285 | 280 | 290 |
| 4 | 10 | 295 | 305 | 300 | 310 |
Fixing the Excel Pivot Table Approach
If you want to use Excel's Pivot Table instead, follow these steps:
- Select your original data range and insert a Pivot Table.
- In the PivotTable Fields pane:
- Drag
depthto the Rows area. - Drag
densityto the Columns area. - Drag both
tb10andtb18to the Values area (you'll see two entries: "Sum of tb10" and "Sum of tb18").
- Drag
- The pivot table will now have a multi-level column header: the top level is
tb10/tb18, and the second level is10/20. - Rename the columns to match your desired format (e.g., "den10_tb10" instead of "Sum of tb10" for density 10).
- If you need the
densitycolumn with value 10, add it manually next to thedepthcolumn (since it's redundant here, but matches your target layout).
内容的提问来源于stack exchange,提问作者srinivas
相关产品推荐
相关产品推荐

