LoginSignup
0
0

More than 1 year has passed since last update.

Pandas: データフレームについて--10: データの置換

Posted at

データの置換

欠損値 NaN の置換については, 「Pandas: データフレームについて--02: 欠損値の扱い」を参照のこと。

import pandas as pd
df = pd.DataFrame({
    'a': [1, 2, 3, 4, 5],
    'b': [1.2, 3.4, 5.6, 7.8, 9.0]
})
df
a b
0 1 1.2
1 2 3.4
2 3 5.6
3 4 7.8
4 5 9.0

1. 条件式が True の場合に,指定した値で置き換える

Usage: mask(cond, other=nan, inplace=False, axis=None,
            level=None, errors='raise', try_cast=<no_default>)
df['a'].mask(df['b'] > 4, 999)
0      1
1      2
2    999
3    999
4    999
Name: a, dtype: int64

2. 条件式が False の場合に,指定した値で置き換える

Usage: where(cond, other=nan, inplace=False, axis=None,
             level=None, errors='raise', try_cast=<no_default>)
df['a'].where(df['b'] > 4, 999)
0    999
1    999
2      3
3      4
4      5
Name: a, dtype: int64

3. 指定した値を置き換える

Usage: replace(to_replace=None, value=None, inplace: 'bool' = False,
               limit=None,regex: 'bool' = False, method: 'str' = 'pad') 
df.replace([1, 3, 7.8], 999)
a b
0 999 1.2
1 2 3.4
2 999 5.6
3 4 999.0
4 5 9.0

指定した列だけを対象にする場合

df.replace({'b': {3.4: 888, 7.8: 777}})
a b
0 1 1.2
1 2 888.0
2 3 5.6
3 4 777.0
4 5 9.0

4. もっと知りたい人

help(df.mask)    # Help on method mask in module pandas.core.frame
help(df.where)   # Help on method where in module pandas.core.frame
help(df.replace) # Help on method replace in module pandas.core.frame
0
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
0
0