在PowerQuery/M中插入一个包含值列表的新列

5

如果我有以下源代码:

#"My Source" = Table.FromRecords({
        [Name="Jared Smith", Age=24],
        [Name = "Tom Brady", Age=44],
        [Name="Hello Tom", Age = null],
        [Name = "asdf", Age = "abc"]
    }),

我该如何从一列值中添加新的列,例如:

Table.AddColumn(#"My Source", "New Col", {'x', 'y', 'z', null})

现在我的表格需要三列,应该如何实现?

你好。你找到一种在不使用索引的情况下追加列的方法了吗?似乎只是为了添加新列而创建一个索引有些过度了。谢谢。 - Confounded
3个回答

5

这里有另一种方法。它的开始类似于 Ron 使用的方法,通过添加一个索引,但是它不使用合并操作,而是将索引作为适当列表项的参照。

let
    Source1 = Table.FromRecords({
        [Name="Jared Smith", Age=24],
        [Name = "Tom Brady", Age=44],
        [Name="Hello Tom", Age = null],
        [Name = "asdf", Age = "abc"]
    }),
    #"Added Index" = Table.AddIndexColumn(Source1, "Index", 0, 1),
    #"Added Custom" = Table.AddColumn(#"Added Index", "Custom", each {"x", "y", "z", null}{[Index]}),
    #"Removed Columns" = Table.RemoveColumns(#"Added Custom",{"Index"})
in
    #"Removed Columns"

2

我是一个PQ初学者,所以可能有更有效的方法,但这里有一个:

  • 为每个表添加一个索引列
  • 使用索引列作为关键字合并两个表
  • 删除索引列

let
    Source1 = Table.FromRecords({
        [Name="Jared Smith", Age=24],
        [Name = "Tom Brady", Age=44],
        [Name="Hello Tom", Age = null],
        [Name = "asdf", Age = "abc"]
    }),
    #"Added Index" = Table.AddIndexColumn(Source1, "Index", 0, 1),
    Source2 = Table.FromRecords({
        [New="x"],
        [New = "y"],
        [New = "z"],
        [New = null]
    }),
    #"Added Index2" = Table.AddIndexColumn(Source2, "Index", 0, 1),
    Merge = Table.Join(#"Added Index", "Index",#"Added Index2", "Index"),
    #"Removed Columns" = Table.RemoveColumns(Merge,{"Index"})
in
    #"Removed Columns"

enter image description here


@David542 是的。如果你有大表格,应该尝试使用合并方法和你接受的答案中的方法来看哪一个更快。 - Ron Rosenfeld
谢谢,合并应该会更快(我猜的,不过需要测试才能确定)。这基本上是为了以一种快速的方式轻松添加额外的数据。 - David542

1

这里有另一种解决方案

let
    #"My Source" = Table.FromRecords({
        [Name="Jared Smith", Age=24],
        [Name = "Tom Brady", Age=44],
        [Name="Hello Tom", Age = null],
        [Name = "asdf", Age = "abc"]
    }),
    AddListAsColumn = Table.FromColumns(Table.ToColumns(#"My Source") & {{"x", "y", "z", null}}, Table.ColumnNames(#"My Source") & {"New Col"})
in AddListAsColumn

根据您的需求,您可能需要缓冲“我的源代码”。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接