Python Forum

Full Version: Pandas fillna based on conditions
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am pretty new at using Pandas, so I was wondering if anyone could help me with the below.

Let's say I have this dataframe:

import pandas as pd
import numpy as np

data = [
    ['Rabbit', 2, 2],
    ['Dog', 5, 5.5],
    ['Dog', 3, 2.8],
    ['Cat', np.nan, np.nan],
    ['Cat', np.nan, np.nan],
    ]

df = pd.DataFrame(columns=["Type", "Weight_April", "Weight_May"], data=data)
With other columns for weights for all months up until January.

What I want to do is replace all the nan values of types == 'Cat' with the weights of the types== 'Dog' so that my data would look like this:
import pandas as pd
import numpy as npdata = [
    ['Rabbit', 2, 2],
    ['Dog', 5, 5.5],
    ['Dog', 3, 2.8],
    ['Cat', 5, 5.5],
    ['Cat', 5, 2.8],
    ]

df = pd.DataFrame(columns=["Type", "Weight_April", "Weight_May"], data=data)
Any advice? Thanks!
You can do this as follows:

df.loc[df.Type=='Cat', ["Weight_April", "Weight_May"]] = df.loc[df.Type == 'Dog', ["Weight_April", "Weight_May"]].values
It should be noted that there is special dataframe's method fillna that perfectly do this work.

df.fillna(df.mean(), inplace=True)
# replace nans with column's mean values