Search code examples
pythonpandasnanfill

Fill in NaN only in those rows that contain in two Columns NaN


enter image description hereI would like just to fill the rows (index 3) that in both columns contain NaN (with the 1st of January-1 01 ) Leaving the other rows with NaNs.

problem:

index---day----month----year

0-------Nan----03--------93

1-------18-----Nan-------85

2-------8------7---------71

3-------Nan------Nan------75

solution

index---day----month----year

0-------Nan----03--------93

1-------18-----Nan-------85

2-------8------7---------71

3-------1------01--------75

Solution

  • You can do it with 3 steps. First, you replace all NaN values in only one column by the letter "-" (or an other letter that is not used in your dataset). Secondly, you fill NaN values in columns "day" and "month" with "1" and "01". Finally, you recreate NaN values for "-" values. The code looks like that :

    import numpy as np
    import pandas as pd
    
    data = {
        "day" : [np.nan, "18", "08", np.nan, np.nan],
        "month" : ["03", np.nan, "7", np.nan, np.nan],
        "year" : ["93", "85", "71", "75", "56"],
    }
    df = pd.DataFrame(data)
    values = {'day': "1", 'month': "01"}
    df = df.fillna("-", limit=1).fillna(value=values).replace("-", np.nan)
    df