10
4

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.

Python list.sorted() における NaN値の扱い

Last updated at Posted at 2018-08-15

Pythonのlist.sorted()は、比較要素にNaN値が含まれると正しくソートできない。比較要素内にNaN値がある場合は、それらを適当な値に置き換える必要がある。

サンプルコード

import numpy as np

a1 = [1, 2, 9, 3, 2, np.nan, np.nan] # 例題 a1
a2 = [1, np.nan, 2, 9, 3, 2, np.nan] # 例題 a2

# 単純なSortの実行
ng1 = sorted(a1, key=lambda x: x)
ng2 = sorted(a2, key=lambda x: x)

# NaN値を置き換えてのSortの実行
ok1 = sorted(a1, key=lambda x: np.inf if np.isnan(x) else x)
ok2 = sorted(a2, key=lambda x: np.inf if np.isnan(x) else x)

print("NG:", ng1, ng2) # 例題 a2 を正しくソートできない
print("OK:", ok1, ok2) # 両例題とも正しくソートできる

実行結果

NG: [1, 2, 2, 3, 9, nan, nan] [1, nan, 2, 2, 3, 9, nan]
OK: [1, 2, 2, 3, 9, nan, nan] [1, 2, 2, 3, 9, nan, nan]
10
4
4

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
10
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?