LoginSignup
2
0

More than 1 year has passed since last update.

Power Query workout - Table.TransformColumnTypes

Last updated at Posted at 2022-07-07

テーブルに含まれる列のタイプを変更するだけではなく、列に含まれる値に対し対応する変換が行われる。そうしないと値変換時のエラー検出ができないですからね。

Table.TransformColumnTypes(
    table as table,
    typeTransformations as list,
    optional culture as nullable text
) as table

パラメータ

culture

Culture.Current と異なる culture、もしくは、明示的な culture を指定できる。ただし、culture パラメータへの引数はひとつだけ。なので、必要に応じて分割。

Power Query
let
    Source = Table.FromColumns(
        {
            {"2022年7月7日"},
            {"2022年7月7日 木曜日"},
            {"令和4年7月7日"}
        },
        {"Date1", "Date2", "Date3"}
    ),
    ChangedTypeCurrentCulture = Table.TransformColumnTypes(
        Source,{{"Date1", type date}}
    ),
    ChangedTypeWithLocale = Table.TransformColumnTypes(
        ChangedTypeCurrentCulture,
        {
            {"Date2", type date},
            {"Date3", type date}
        },
        "ja-JP"
    )
in
    ChangedTypeWithLocale

typeTransformations

typeTransformations パラメータの引数は list。ネストしたリストで複数の列に対する処理を記述できる。
リストアイテムひとつめは列名、ふたつめは列のタイプ

Power Query
{
    {"Column1", Int64.Type},
    {"Column2", Date.Type}
}

となるとき、Column1 列のタイプは Int64.Type になり、列に含まれる値には Int64.From が適用される。結果、Table.TransfromColumnTypes により 値変換時のエラー検出ができるようになっている。よく観察すれば、この動作は明確にできる。

Column1 列に含まれる値は、Int64.From で変換されるを確認

let
    Source = Table.FromColumns(
        {
            {0.4, 0.5, 1.4, 1.5, 2.4, 2.5}
        },
        {"Column1"}
    ),
    AddedColumn2 = Table.AddColumn(
        Source,
        "Column2",
        each Int64.From([Column1]),
        Int64.Type
    ),
    AddedColumn3 = Table.AddColumn(
        AddedColumn2,
        "Column3",
        each Int64.From([Column1], null, RoundingMode.AwayFromZero ),
        Int64.Type
    ),
    ChangedTypeColumn1 = Table.TransformColumnTypes(
        AddedColumn3,
        {{"Column1", Int64.Type}}
    )
in
    ChangedTypeColumn1

数値の丸めが異なることがわかる。Int64.From 既定の変換動作になってるよね。

Column1 Column2 Column3
0 0 0
0 0 1
1 1 1
2 2 2
2 2 2
2 2 3

Currency.Type への変換でも Currency.From 既定の丸め動作になるし、タイムゾーンが関与する列の変換だと環境により異なる変換がされるよね。

Power Query
Table.TransformColumnTypes(
    Table.FromValue("2022-07-07T14:53:00Z"),
    {"Value", type datetime}
)

思ったこと🙄

Table.TransfromColumnTypes で行われる値の変換動作は、

  • Culture.Current で確認できるロケール
  • 動作環境
  • Power Query 既定の動作

なのですよ。値の変換は必要になるまで実施されない。大事なことなのでもう一度、値の変換は必要になるまで実施されない。

その他

2
0
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
2
0