Python Forum
Pandas fillna based on conditions
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Pandas fillna based on conditions
#1
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!
Reply
#2
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Pandas Dataframe Filtering based on rows mvdlm 0 1,396 Apr-02-2022, 06:39 PM
Last Post: mvdlm
  Python Based ETL Using Pandas HyperSpeed 0 1,536 Jan-13-2022, 04:18 PM
Last Post: HyperSpeed
  New Dataframe Column Based on Several Conditions nb1214 1 1,783 Nov-16-2021, 10:52 PM
Last Post: jefsummers
  update values in one dataframe based on another dataframe - Pandas iliasb 2 9,100 Aug-14-2021, 12:38 PM
Last Post: jefsummers
  Pandas Data frame column condition check based on length of the value aditi06 1 2,655 Jul-28-2021, 11:08 AM
Last Post: jefsummers
  Pandas - Dynamic column aggregation based on another column theroadbacktonature 0 3,011 Apr-17-2020, 04:54 PM
Last Post: theroadbacktonature
  Grouping data based on rolling conditions kapilan15 0 1,930 Jun-05-2019, 01:07 PM
Last Post: kapilan15
  Splitting values in column in a pandas dataframe based on a condition hey_arnold 1 4,139 Jul-24-2018, 02:18 PM
Last Post: hey_arnold
  Updating df rows based on 2 conditions stretch 1 3,108 May-02-2018, 09:15 AM
Last Post: volcano63

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020