使用Excel或Python-Pandas实现动态数据透视/分组转换需求
Great question! Manually reshaping this kind of paired-column data is super tedious and error-prone—automating it is absolutely the right call. Here are two robust solutions to get your desired output:
Power Query (built into Excel 2016+) is perfect for this kind of data transformation without writing any code. Here's how to do it step-by-step:
Load your data into Power Query:
- Select your entire data range (including headers).
- Go to the
Datatab → ClickFrom Table/Range(this opens the Power Query Editor).
Clean up unnecessary columns:
- Right-click the
s.Nocolumn header → SelectRemove(we don't need this for the final output).
- Right-click the
Unpivot paired Source/Price columns:
- Hold Ctrl to select all columns except
Item Name. - Go to the
Transformtab → ClickUnpivot Columns→Unpivot Only Selected Columns. This creates two new columns:Attribute(e.g., "Source1", "Price1") andValue(the website name or price).
- Hold Ctrl to select all columns except
Add a helper column to pair Source/Price entries:
- Go to the
Add Columntab → ClickCustom Column. - Enter this formula to extract the number suffix from the Attribute column:
Text.Select([Attribute], {"0".."9"}) - Name this new column
PairIDand click OK.
- Go to the
Pivot to combine Source/Price pairs:
- Select the
Attributecolumn. - Go to the
Transformtab → ClickPivot Column. - Set
Values ColumntoValue, checkDon't aggregateunder Advanced options, then click OK. You'll now haveSourceandPricecolumns paired byPairID.
- Select the
Pivot to get websites as columns:
- Select the
Sourcecolumn. - Go to the
Transformtab → ClickPivot Column. - Set
Values ColumntoPrice, checkDon't aggregate, then click OK.
- Select the
Final cleanup:
- Replace null values with "na": Go to
Transform→Replace Values, setValue To FindtonullandReplace Withtona. - Click
Close & Loadto export the transformed data back to an Excel sheet.
- Replace null values with "na": Go to
If you prefer using code, Pandas has built-in functions to handle this reshaping in just a few lines:
Import Pandas and load your data:
import pandas as pd # Load data (use pd.read_excel if your data is in an Excel file) df = pd.read_csv("your_data_file.csv")Reshape to pair Source/Price columns:
Usewide_to_longto convert the wide-format paired columns into a long format where each Source is matched with its Price:df_long = pd.wide_to_long( df.drop("s.No", axis=1), # Remove the unused s.No column stubnames=["Source", "Price"], # Prefixes of the paired columns i="Item Name", # Column to group rows by j="pair", # Temporary column to track pair numbers sep="" # No separator between prefix and number (e.g., Source1 instead of Source_1) ).reset_index()Pivot to get websites as columns:
Convert the long format back to a wide format with websites as columns:df_pivot = df_long.pivot( index="Item Name", columns="Source", values="Price" ).reset_index()Clean up the output:
Replace missing values with "na" and tidy up column names:df_final = df_pivot.fillna("na") df_final.columns.name = None # Remove the "Source" header label # Print or save the result print(df_final) df_final.to_csv("transformed_data.csv", index=False)
This will give you exactly the output format you're looking for, with zero manual data entry errors.
内容的提问来源于stack exchange,提问作者Rams

