功率查询-特定文本的累积计数器(索引)

时间:2018-12-19 15:49:39

标签: excel powerquery

在Excel的powerquery编辑器中,我有两列。两者都有随机字符串。 看到这张图片:

enter image description here

我想用运行中的计数器替换特定字符串的所有值,在这种情况下:'a'。其他值应替换为“ null”。最终结果应为以下图像:

enter image description here

特定规则:

  • 代码需要通用;列和行的数量将有所不同。

2 个答案:

答案 0 :(得分:2)

这将适用于任何数量的列和行。

let Filter="a",
Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
Columns = Table.ColumnNames(Source),
#"Added Index1" = Table.AddIndexColumn(Source, "Indexz", 0, 1),
Unpivot = Table.UnpivotOtherColumns(#"Added Index1", {"Indexz"}, "Attribute", "Value"),
Grouped = Table.Group(Unpivot, {"Attribute","Value"}, {{"Count", each Table.AddIndexColumn(_, "Index",1,1), type table}}),
#"Expanded Count" = Table.ExpandTableColumn(Grouped, "Count", {"Indexz", "Index"}, {"Indexz", "Index"}),
#"Added Custom" = Table.AddColumn(#"Expanded Count", "Count", each if [Value]=Filter then [Index] else null),
#"Removed Columns" = Table.RemoveColumns(#"Added Custom",{"Value","Index"}),
#"Pivoted Column" = Table.Pivot(#"Removed Columns", List.Distinct(#"Removed Columns"[Attribute]), "Attribute", "Count"),
#"Removed Columns1" = Table.RemoveColumns(#"Pivoted Column",{"Indexz"})
in #"Removed Columns1"

答案 1 :(得分:0)

您可以通过为每列的每个值创建一个分区,然后在该分区中添加索引来做到这一点。对两列重复以上操作,然后在条件匹配时用索引替换值:

let
    Source = MySource,
    Criteria = "a",
    #"Added Index" = Table.AddIndexColumn(Source, "SortIndex", 1, 1),
    #"Partition 2" = Table.Group(#"Added Index", {"column 2"}, {{"Partition", each Table.AddIndexColumn(_, "Index",1,1), type table}}),
    #"Expanded Partition 2" = Table.ExpandTableColumn(#"Partition 2", "Partition", {"column 1", "SortIndex", "Index"}, {"column 1", "SortIndex", "Index 2"}),
    #"Sort 2" = Table.Sort(#"Expanded Partition 2",{{"SortIndex", Order.Ascending}}),
    #"Partition 1" = Table.Group(#"Sort 2", {"column 1"}, {{"Partition", each Table.AddIndexColumn(_, "Index",1,1), type table}}),
    #"Expand Partition 1" = Table.ExpandTableColumn(#"Partition 1", "Partition", {"column 2", "SortIndex", "Index 2", "Index"}, {"column 2", "SortIndex", "Index 2", "Index 1"}),
    #"Sort 1" = Table.Sort(#"Expand Partition 1",{{"SortIndex", Order.Ascending}}),
    #"Replaced 1" = Table.ReplaceValue(#"Sort 1",each [column 1], each if [column 1] = Criteria then [Index 1] else null, Replacer.ReplaceValue,{"column 1"}),
    #"Replaced 2" = Table.ReplaceValue(#"Replaced 1",each [column 2], each if [column 2] = Criteria then [Index 2] else null, Replacer.ReplaceValue,{"column 2"}),
    #"Removed Columns" = Table.RemoveColumns(#"Replaced 2",{"SortIndex", "Index 2", "Index 1"})
in
    #"Removed Columns"