You can obtain your desired output using Power Query, available in Windows Excel 2010+ and Office 365 Excel
- Select some cell in your original table
Data => Get&Transform => From Table/Range or From within sheet
- When the PQ UI opens, navigate to
Home => Advanced Editor
- Make note of the Table Name in Line 2 of the code.
- Replace the existing code with the M-Code below
- Change the table name in line 2 of the pasted code to your "real" table name
- Examine the code comments, and also the
Applied Steps window, to better understand the algorithm and steps
M Code
let
//Get data => change table name in next line to your actual table name
Source = Excel.CurrentWorkbook(){[Name="Table2"]}[Content],
//Set the column data types=> ID=integer; other columns =>text
#"Changed Type" = Table.TransformColumnTypes(Source,
{"ID", Int64.Type} & List.Transform(List.RemoveFirstN(Table.ColumnNames(Source),1), each {_, type text})),
//Unpivot all except the ID column
#"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Changed Type", {"ID"}, "Attribute", "Value"),
//Split the Attribute column on the underscore to have lists of identical attributes
#"Split Column by Delimiter" = Table.SplitColumn(#"Unpivoted Other Columns", "Attribute",
Splitter.SplitTextByDelimiter("_", QuoteStyle.Csv), {"Attribute"}),
//Group by ID
// Then aggregate to create list of records where each record consists of each pair of values
// effectively Pivoting with no aggregation
#"Grouped Rows" = Table.Group(#"Split Column by Delimiter", {"ID"}, {
{"pivot", (t)=>let
recs = List.Generate(
()=> [r=Record.FromList({t[Value]{0},t[Value]{1}},{t[Attribute]{0},t[Attribute]{1}}),idx=0],
each [idx]<Table.RowCount(t),
each [r=Record.FromList({t[Value]{[idx]+2},t[Value]{[idx]+3}},{t[Attribute]{[idx]+2},t[Attribute]{[idx]+3}}),
idx=[idx]+2],
each [r])
in recs, type list}
}),
//expand the list of records to new rows
#"Expanded pivot" = Table.ExpandListColumn(#"Grouped Rows", "pivot"),
//expand the records to new columns
#"Expanded pivot1" = Table.ExpandRecordColumn(#"Expanded pivot", "pivot", {"Name", "Gender"}, {"Name", "Gender"}),
//set the data types
#"Changed Type1" = Table.TransformColumnTypes(#"Expanded pivot1",{{"Name", type text}, {"Gender", type text}})
in
#"Changed Type1"
