【问题标题】:How to use PowerQuery to randomly select a proportion of rows for each unique value in a specific column?如何使用 Power Query 为特定列中的每个唯一值随机选择一定比例的行?
【发布时间】:2021-11-09 07:11:13
【问题描述】:

我在 Python 中完成了所有这些工作,但我要离开公司,我想留下一个流程,让技术水平比我还低的人来管理。

我已经编写了有关如何在 Excel 中使用 Power Query(获取和转换数据)合并数百个 Excel 工作表的说明。然后我让它们“关闭并加载”到 Excel 工作表中……数据由大约 9000 行和 >20 列组成。一列,称为“姓名”,= 同事姓名(大约有 20 个唯一姓名)。

现在我需要随机获取每个同事行的 10%。 (在 Python 中,我使用了 groupby 和示例,here。)我可以在 Excel 工作表中通过添加一个名为“Rand No”的“帮助行”来执行此操作,其中包含公式 =RAND(),然后使用此数组公式(控制+Shift+Enter):=IF([@[Rand No]]>=LARGE((--([@Name]=[Name])*[Rand No]),COUNTIF([Name],[@Name])/10),"Randomised","")。 但我只是想知道如何在 PowerQuery 中进行这种随机化,因为当我们合并所有这些工作表时,我们已经打开了 PQ 编辑器。我猜它会比使用普通 Excel 公式更复杂——但我错了吗?

【问题讨论】:

  • 你试过什么?我认为Group by Name => add a column with random numbers to each subgroup => sort by that column => Select the first 10% of the rows 应该这样做。

标签: excel random powerquery


【解决方案1】:

这是一种略有不同的方法。

  • 我创建了一个List 的随机数,其计数与表格行数相同
  • 将该列表作为列添加到原始表中
  • 然后按名称分组,按随机列对每个子组进行排序,然后删除除 N% 以外的所有行。

这通常会在每次刷新查询时提供不同的输出。

在我的查询中,我生成了数据,作为名称列表和值列表,但您可以轻松地从任何来源读取数据。

M 代码
根据@horseyride 的建议编辑

let

//read in the table.
// I created a table, but you can obtain it from any source
    Source = Table.FromColumns({
                List.Repeat({"A".."Z"},10), List.Numbers(0,260)},
                type table[Name=text,Value=Int64.Type]),

//Add buffered random number column to the table
    random = List.Buffer(List.Random(Table.RowCount(Source))),
    newTbl = Table.FromColumns(
            Table.ToColumns(Source) & {random},
            type table [Name=text, Value=Int64.Type, Random=number]
    ),

//Group by Name, then extract the top N by sorting and removing (1-N) rows
    N=0.1,

    grp = Table.Group(newTbl,"Name",{{
        "group", each Table.RemoveRows(Table.Sort(_,{"Random",Order.Descending}),0, 
           Number.RoundTowardZero(Table.RowCount(_)*(1-N)))
    }}),

//Expand the Value Column
//  You may need to expand more columns -- just don't check Name or Random
    #"Expanded group" = Table.ExpandTableColumn(grp, "group", {"Value"}, {"Value"})
in
    #"Expanded group"

【讨论】:

  • 当行数不是偶数时,Table.RowCount(_)*(1-N) 是否适合您? (87 行,n=.10,删除 8.7 行)这就是为什么我试图在表行数上使用 Number.IntegerDivide()
  • @horseyride 感谢您指出这一点。我通过四舍五入解决了这个问题。
  • 哈!这些年来,我从来没有注意到这个功能!
猜你喜欢
  • 2021-12-04
  • 2019-09-13
  • 2011-05-18
  • 2015-10-15
  • 2011-06-07
  • 2018-03-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多