Excel PowerQuery: How to unpivot or transpose a huge table into a readable format for analysis

后端 未结 2 419
孤城傲影
孤城傲影 2021-01-17 02:56

I have this table that looks similar to this:

And I want to transform it so that it looks like this:

The idea is to unpivot( or transpose) the tabl

2条回答
  •  悲哀的现实
    2021-01-17 03:31

    Before loading into PowerQuery, concatenate the headers to the empty row after [Programe Name] using a delimiter (space). You can use the TEXTJOIN function to do this if you use office365. The result looks something like this (I did not copy all your data):

    Import this range into PowerQuery and perform the following steps (Do not check the my table has headers checkbox)

    1. Remove top 2 rows (Home tab > Remove Rows)
    2. Use first row as headers (Home tab > Use First Row as Headers)
    3. Select the first column
    4. Unpivot other columns (dropdown menu unpivot columns on Transform Tab)
    5. Split the [Attribute] column by delimiter (space) (Home tab > Split Column)
    6. Change column names
    7. Move City column to the left (rightclick column > move > left)

    The script looks like this:

    let
        Source = Excel.CurrentWorkbook(){[Name="table"]}[Content],
        #"Changed Type" = Table.TransformColumnTypes(Source,{{"Column1", type text}, {"Column2", type any}, {"Column3", type any}, {"Column4", type any}, {"Column5", type any}, {"Column6", type any}, {"Column7", type any}, {"Column8", type any}, {"Column9", type any}}),
        #"Removed Top Rows" = Table.Skip(#"Changed Type",2),
        #"Promoted Headers" = Table.PromoteHeaders(#"Removed Top Rows", [PromoteAllScalars=true]),
        #"Changed Type1" = Table.TransformColumnTypes(#"Promoted Headers",{{"Program Name", type text}, {"NY Budget", Int64.Type}, {"NY Revenue", Int64.Type}, {"NY Cost", Int64.Type}, {"NY Margin", Int64.Type}, {"LA Budget", Int64.Type}, {"LA Revenue", Int64.Type}, {"LA Cost", Int64.Type}, {"LA Margin", Int64.Type}}),
        #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Changed Type1", {"Program Name"}, "Attribute", "Value"),
        #"Split Column by Delimiter" = Table.SplitColumn(#"Unpivoted Other Columns", "Attribute", Splitter.SplitTextByDelimiter(" ", QuoteStyle.Csv), {"Attribute.1", "Attribute.2"}),
        #"Changed Type2" = Table.TransformColumnTypes(#"Split Column by Delimiter",{{"Attribute.1", type text}, {"Attribute.2", type text}}),
        #"Renamed Columns" = Table.RenameColumns(#"Changed Type2",{{"Attribute.1", "City"}, {"Attribute.2", "Description"}}),
        #"Reordered Columns" = Table.ReorderColumns(#"Renamed Columns",{"City", "Program Name", "Description", "Value"})
    in
        #"Reordered Columns"
    

    And this is the result (in the Power Query Editor)

提交回复
热议问题