How to replace multiple values in a Pandas DataFrame?
0

How to replace multiple values in a Pandas DataFrame?

This recipe helps you replace multiple values in a Pandas DataFrame
In [1]:
## How to replace multiple values in a Pandas DataFrame
def Snippet_104():
    print()
    print(format('How to replace multiple values in a Pandas DataFrame','*^82'))

    import warnings
    warnings.filterwarnings("ignore")

    # load libraries
    import pandas as pd
    import numpy as np

    # Create dataframe
    raw_data = {'first_name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
                'last_name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze'],
                'age': [42, 52, 36, 24, 73],
                'preTestScore': [-999, -999, -999, 2, 1],
                'postTestScore': [2, 2, -999, 2, -999]}

    df = pd.DataFrame(raw_data, columns = ['first_name', 'last_name', 'age', 'preTestScore', 'postTestScore'])
    print(); print(df)

    # Replace all values of -999 with NAN
    print(); print(df.replace(-999, np.nan))

    # Replace all values of -999 with 0
    print(); print(df.replace(-999, 0))

Snippet_104()
***************How to replace multiple values in a Pandas DataFrame***************

  first_name last_name  age  preTestScore  postTestScore
0      Jason    Miller   42          -999              2
1      Molly  Jacobson   52          -999              2
2       Tina       Ali   36          -999           -999
3       Jake    Milner   24             2              2
4        Amy     Cooze   73             1           -999

  first_name last_name  age  preTestScore  postTestScore
0      Jason    Miller   42           NaN            2.0
1      Molly  Jacobson   52           NaN            2.0
2       Tina       Ali   36           NaN            NaN
3       Jake    Milner   24           2.0            2.0
4        Amy     Cooze   73           1.0            NaN

  first_name last_name  age  preTestScore  postTestScore
0      Jason    Miller   42             0              2
1      Molly  Jacobson   52             0              2
2       Tina       Ali   36             0              0
3       Jake    Milner   24             2              2
4        Amy     Cooze   73             1              0