2
0

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 1 year has passed since last update.

欠損値 missing の置換

Last updated at Posted at 2023-02-13

データフレームの missing の置換(その2)

Julia のデータフレームのとある列の missing を別の値に置換する方法。

以下のようなデータフレームを例に取る。

using DataFrames

df0 = DataFrame(a=[1, 2, missing, 4, 5], b=["foo", "bar", "baz", missing, "zoo"])
5×2 DataFrame
Row a b
Int64? String?
1 1 foo
2 2 bar
3 missing baz
4 4 missing
5 5 zoo

coalesce 関数を使う。

https://segakuin.com/oracle/function/coalesce.html
COALESCEとは、複数指定された引数のうち、NULLではない最初の値を返すSQL関数である。

なんの略語かと思ったが,
https://ejje.weblio.jp/content/coalesce
癒合(ゆごう)する、合体する、合同する

とのことで,COALESCE の意はないように見える。

Julia でも COALES と同じ働きをする関数が用意されている。

個々の列の missing を置き換える例を示す。

df1 = copy(df0)
df1.a = coalesce.(df1.a, 999)
df1.b = coalesce.(df1.b, "batman")
df1
5×2 DataFrame
Row a b
Int64 String
1 1 foo
2 2 bar
3 999 baz
4 4 batman
5 5 zoo

どの missing も同じ値で置き換える場合は,以下のようにする。

df2 = copy(df0)
df2 = coalesce.(df2, 0)
df2
5×2 DataFrame
Row a b
Int64 Any
1 1 foo
2 2 bar
3 0 baz
4 4 0
5 5 zoo

効率は良くないが,基本的には以下のようにすればよい。missing かどうかは ismissing() を使う。x == missing のような比較はできない。

df3 = copy(df0)
for i in 1:nrow(df3)
    if ismissing(df3.a[i])
        df3.a[i] = 99999
    end
end
df3
5×2 DataFrame
Row a b
Int64? String?
1 1 foo
2 2 bar
3 99999 baz
4 4 missing
5 5 zoo

欠損値であるかどうかのベクトルを ismissing() で指定して置き換え数値を代入することもできる。

df4 = copy(df0)
df4.a[ismissing.(df4.a)] .= 999999
df4
5×2 DataFrame
Row a b
Int64? String?
1 1 foo
2 2 bar
3 999999 baz
4 4 missing
5 5 zoo

結論としては coalesce() を使うのが妥当である。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?