Pandas fillna based on conditions - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Data Science (https://python-forum.io/forum-44.html) +--- Thread: Pandas fillna based on conditions (/thread-18027.html) |
Pandas fillna based on conditions - amyd - May-03-2019 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! RE: Pandas fillna based on conditions - scidam - May-03-2019 You can do this as follows: df.loc[df.Type=='Cat', ["Weight_April", "Weight_May"]] = df.loc[df.Type == 'Dog', ["Weight_April", "Weight_May"]].valuesIt 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 |