1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

テーブルの列同士の計算をレコード関数で

Last updated at Posted at 2019-04-06

やりたいこと

テーブル内の特定の複数列に,同じ行の特定の列の値をかけ,その結果は新しい列として持つ,というもの.イメージは下記画像のとおり.
※Power BI勉強会 Power Query 秘密特訓「虎の穴」 #3にて,お話の出た計算方法の再現です.
キャプチャ.JPG

モデルデータ

なんでもいいんですが,この際,最近のマイブームのList.Generate()を使い,テーブルを作りました.

モデルデータ
let
    ソース = List.Generate(
                ()=>[index=0,a=100,b=200,c=150,rate=1.5],
                each [index]<50,
                each [index=[index]+1,a=[a]+10,b=[b]+11,c=[c]+5,rate=[rate]+0.1]
    ),
    テーブルに変換済み = Table.FromList(ソース, Splitter.SplitByNothing(), null, null, ExtraValues.Error),
    #"展開された Column1" = Table.ExpandRecordColumn(テーブルに変換済み, "Column1", 
                    {"index", "a", "b", "c", "rate"}, {"index", "a", "b", "c", "rate"})
in
    #"展開された Column1"

↓できあがるテーブル
キャプチャ2.JPG

各行の計算結果をレコードで持つ列を追加するコード

下記コードでレコード持ちの状態になります.expandはUIでやったほうが列名付ける手間が省けるので,書いてません.

let
    ソース = モデルテーブル,
    列追加 = Table.AddColumn(ソース, "A国", 
                        (rec)=>Record.TransformFields(rec,{
                            {"a",each _*rec[rate]},
                            {"b",each _*rec[rate]},
                            {"c",each _*rec[rate]}
                            })
                        )
in
    列追加

別法:列名のリストを渡して一気に計算させてみた

対象とする列名のリストを引数にしてやらせることも出来そうですね.
気が向いたら,記事に追加するかもです.

↓書き上げました.(追記2019.4.8)
列が多かったり,繰り返しこの計算をする場面が出るとかだと,活躍するかもしれません.
今回は引数が入り混じらないので,普通にeachと_で書きました.(もちろん上のコードと同じく手法も可)

列名リストを渡す版
let
    ソース = モデルテーブル,
    列追加 = Table.AddColumn(ソース, "カスタム", 
                each List.Accumulate({"a","b","c"},
                                        [],
                                        (state,current)=>
                                        Record.AddField(state,current,
                                            Record.Field(_,current)*_[rate]
                                        )
                )
    )
in
    列追加

補足:List.Accumulate関数

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?