You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Power Query中基于字典表为Risks表添加分类列的方法

在PowerBI中无需Python实现风险项关键词匹配分类

方案一:Power Query(M语言)处理(适合数据清洗阶段)

这种方法适合在数据加载环节完成分类匹配,步骤如下:

  1. 预处理关键词字典
    先把Dictionary表的key_words列拆分(如果关键词用逗号/分号等分隔),确保每行仅保留一个关键词:
let
    Source = Dictionary,
    // 按逗号拆分关键词并展开为单行
    SplitKeywords = Table.ExpandListColumn(Table.SplitColumn(Source, "key_words", Splitter.SplitTextByDelimiter(",", QuoteStyle.Csv), {"key_words"}), "key_words"),
    // 去除关键词前后空格
    TrimKeywords = Table.TransformColumns(SplitKeywords, {{"key_words", Text.Trim, type text}})
in
    TrimKeywords
  1. 关联风险表与字典表
    将Risks表和预处理后的字典表做模糊匹配,提取对应分类:
let
    Source = Risks,
    // 按"string包含key_words"的条件合并表
    MergeTables = Table.NestedJoin(Source, {"string"}, TrimmedDictionary, {"key_words"}, "Matches", JoinKind.LeftOuter),
    // 展开分类列
    ExpandMatches = Table.ExpandTableColumn(MergeTables, "Matches", {"category"}, {"category"}),
    // 处理一个风险项匹配多分类的情况,合并为逗号分隔的字符串
    GroupAndCombine = Table.Group(ExpandMatches, {"string"}, {{"category", each Text.Combine(List.Distinct([category]), ", "), type text}})
in
    GroupAndCombine

若只需保留第一个匹配的分类,可跳过GroupAndCombine步骤,直接用Table.Distinct去重。

方案二:DAX计算列(适合数据模型中实时计算)

如果需要在报表端动态更新分类,可在Risks表中创建DAX计算列:

仅返回第一个匹配的分类

Category = 
VAR CurrentText = Risks[string]
VAR MatchKeyword = 
    MAXX(
        FILTER(Dictionary, CONTAINSSTRING(CurrentText, Dictionary[key_words])),
        Dictionary[key_words]
    )
RETURN
    IF(ISBLANK(MatchKeyword), "未分类", LOOKUPVALUE(Dictionary[category], Dictionary[key_words], MatchKeyword))

返回所有匹配的分类(逗号分隔)

All_Categories = 
VAR CurrentText = Risks[string]
VAR MatchingCats = 
    FILTER(
        Dictionary,
        CONTAINSSTRING(CurrentText, Dictionary[key_words])
    )
RETURN
    IF(COUNTROWS(MatchingCats) = 0, "未分类", CONCATENATEX(MatchingCats, Dictionary[category], ", "))

注意事项

  • 大小写匹配:若需严格区分大小写,Power Query中移除匹配条件里的Comparer.OrdinalIgnoreCase,DAX中改用CONTAINSSTRINGEXACT替代CONTAINSSTRING。
  • 多词关键词:如果关键词是完整短语(比如"数据泄露"),无需拆分字典表,直接用原表匹配即可。
  • 性能优化:数据量较大时,优先选择Power Query完成匹配,比DAX计算列更高效。

内容的提问来源于stack exchange,提问作者Ruari Patterson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 21:52:55