LoginSignup
0
1

More than 1 year has passed since last update.

シリーズ型.map()とシリーズ型.replace()の違い

Posted at

カラム「fruits」の値を以下の規則性に従って変更する

『grape -> 0』『orange -> 1』『banana -> 2』『melon -> 3』

fruits_dict = {
'grape': 0,
'orange': 1,
'banana': 2,
'melon': 3
}

mapでもreplaceでもどちらでもOK

:o:train_df['fruits'] = train_df['fruits'].replace(fruits_dict)
:o:train_df['fruits'] = train_df['fruits'].map(fruits_dict)

print(train_df['fruits'].value_counts())

0 500

1 200

2 300

3 400

Name: weather, dtype: int64

例外 『grape -> 0』のみにする

fruits_dict = {
'grape': 0
}
:white_circle:train_df['fruits'] = train_df['fruits'].replace(fruits_dict)
print(train_df['fruits'].value_counts())

0 500

orange 200

banana 300

melon 400

Name: weather, dtype: int64


fruits_dict = {
'grape': 0
}
:white_circle:train_df['fruits'] = train_df['fruits'].replace(fruits_dict)
print(train_df['fruits'].value_counts())

0.0 500

となる。これは、grape以外の数値がNANとなるからである。
辞書オブジェクトのキーに含まれない値はNaNとなることに注意する必要がある。

→map()では置換されない値がNaNとなってしまう。replace()では元の値のまま。

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