Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

powerbi - Fill in model year gaps with Power Query in Power BI

I have a column for vehicle model years. It includes data with hyphens (e.g. 2016 - 2020). I would like to change it to a comma delimited list (2016, 2017, 2018, 2019, 2020). Ultimately, I will split it by the delimiter and unpivot all the columns (or split it by rows). I can't find anything on Google to help with that. Any help is appreciated.

question from:https://stackoverflow.com/questions/65942560/fill-in-model-year-gaps-with-power-query-in-power-bi

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The following code starts with the hyphenated start/end years (don't sweat the 'Source' definition...just a table entered directly into PowerQuery editor).

The key steps are splitting the years on the dash and then generating a list based on the start and end years thus separated with the List.Generate function (#"List of Years" line). The magic statement is:

each let start = [StartYear], end = [EndYear] in List.Generate(() => start, each _ <= end, each _ + 1)

The 'let start = [StartYear], end = [EndYear]' is used to copy the value of the field for the respective row under consideration into the variables 'start' and 'end'. This is because the .Generate function is not capable of directly incorporating a field reference. The .Generate function then runs very much like a 'for' loop to create a list of values: initial value is 'start', continue iterating until the list value is less than or equal to 'end', increment by 1.

let
    Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMjIwNNM1MjAyUIqNBQA=", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Column1 = _t]),
    #"Renamed Columns" = Table.RenameColumns(Source,{{"Column1", "HumanData"}}),
    #"HumanData Type" = Table.TransformColumnTypes(#"Renamed Columns",{{"HumanData", type text}}),
    #"Split Years" = Table.SplitColumn(#"HumanData Type", "HumanData", Splitter.SplitTextByDelimiter("-", QuoteStyle.Csv), {"StartYear", "EndYear"}),
    #"Year Types" = Table.TransformColumnTypes(#"Split Years",{{"StartYear", Int64.Type}, {"EndYear", Int64.Type}}),
    #"List of Years" = Table.AddColumn(#"Year Types", "ListOfYears", each let start = [StartYear], end = [EndYear] in List.Generate(() => start, each _ <= end, each _ + 1))
in
    #"List of Years"

Once in the list form, you have flexibility in how to expand in PowerQuery.

Hopefully this helps :).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...