Forum Discussion

anvikuttu's avatar
anvikuttu
Advocate I
5 years ago
Solved

Need help to get the conditional average in power query

Hi, I am a newbie to PowerQuery. I need a M Query solution to the below problem Suppose I have a Country column, Value column. Now I wanted to average the Value column not equal to 0, for each coun...
  • CNENFRNL's avatar
    5 years ago

    Hi, Fowmy's solution surely works. When your dataset consists of 2k+ rows, you might try this,

    let
        Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WCg1W0lEyNFCK1YGxTRFsIyQ2VIk3SBiJDVPuDVfiGIrKNERmQ1Q7OyLEwWwgMxYA", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Country = _t, Value = _t]),
    
        #"Added Custom" = Table.AddColumn(Source, "Custom", each Table.Group(Source, {"Country"}, {{"grouped", each _}}){[Country = [Country]]}[grouped][Value]),
        Avg = Table.TransformColumns(#"Added Custom", {{"Custom", each List.Average(List.RemoveItems(List.Transform(_, Number.From), {0}))}})
    in
        Avg
  • Jimmy801's avatar
    Jimmy801
    5 years ago

    Hello

     

    the simplest thing is to include all in ONE Group-Step... the average except 0 and All rows (to keep the value-column for later)

    Check it out

    let
        Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WCg1W0lEyNFCK1YGxTRFsIyQ2VIk3SBiJDVPuDVfiGIrKNERmQ1Q7OyLEwWwgMxYA", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Country = _t, Value = _t]),
        #"Changed Type" = Table.TransformColumnTypes(Source,{{"Value", type number}}),
        #"Grouped Rows" = Table.Group(#"Changed Type", {"Country"}, {{"Average", each List.Average(List.Select([Value], each _ >0)), type number}, {"AllRows", each _, type table [Country=text, Value=number]}}),
        #"Expanded AllRows" = Table.ExpandTableColumn(#"Grouped Rows", "AllRows", {"Value"}, {"Value"})
    in
        #"Expanded AllRows"

     

    This function of the group-function makes the average without 0

    {"Average", each List.Average(List.Select([Value], each _ >0)), type number}

     

    Copy paste this code to the advanced editor in a new blank query to see how the solution works.

    If this post helps or solves your problem, please mark it as solution (to help other users find useful content and to acknowledge the work of users that helped you)
    Kudoes are nice too

    Have fun

    Jimmy