Forum Discussion

PowerBI_Query's avatar
PowerBI_Query
Icon for Helper II rankHelper II
3 years ago
Solved

Assign custom labels to unpivoted data

My original data looks like below. After unpivoting as shown below Column A, B and C. I want to add a new column D in PQ and assing labels shown in column D based on row numbers e.g row 2 to ...
  • edhans's avatar
    edhans
    3 years ago

    Here you go PowerBI_Query 


    Here is the code:

     

    let
        Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
        #"Promoted Headers" = Table.PromoteHeaders(Source, [PromoteAllScalars=true]),
        #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Promoted Headers", {"Heading 1"}, "Attribute", "Value"),
        RecordCount = Table.RowCount(#"Unpivoted Other Columns"),
        CategoryList = List.Repeat(CategoryLabels, RecordCount/373),
        TableWithCategory = Table.ToColumns(#"Unpivoted Other Columns") & {CategoryList},
        #"Final Table" = Table.FromColumns(TableWithCategory, Table.ColumnNames(#"Unpivoted Other Columns") & {"Category"})
    in
        #"Final Table"

     

     

    For clarity I got rid of the Changed Type step as it had 300+ change types. If you can get away with that, do that after the unpivot, but not the end of the world if done before.

    Here is what I did:

    1. Got the number of records
    2. Repeated the list of category labels in a separate list by the number of records divided by 373. If that is not evenly divisible by 373 you will need to add additional logic to truncate the last time it happens.
    3. Converted the original table to a list of columns, then appended the category list.
    4. Converted that list of columns back to a table and got the column names and reapplied them.

    Here is the file back.