Home > other >  Fillna() inside a function
Fillna() inside a function

Time:07-11

I'm trying to change a function that earlier filled missing years as timestamps (the data-type is int now), to one that would treat the missing years as int , and replace them by fillna().

def nons(row):
    for i in row[['name','year_of_release']]:
        if row['name']=="LEGO Harry Potter: Years 5-7":
            row['year_of_release'].fillna(2012)
        else:
            continue
    return row['year_of_release']

gaming['year_of_release']=gaming.apply(nons,axis=1)

yet it keeps treating it as a timestamp:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_10020/3744296997.py in <module>
      7     return row['year_of_release']
      8 
----> 9 gaming['year_of_release']=gaming.apply(nons,axis=1)

~\anaconda3\lib\site-packages\pandas\core\frame.py in apply(self, func, axis, raw, result_type, args, **kwargs)
   8738             kwargs=kwargs,
   8739         )
-> 8740         return op.apply()
   8741 
   8742     def applymap(

~\anaconda3\lib\site-packages\pandas\core\apply.py in apply(self)
    686             return self.apply_raw()
    687 
--> 688         return self.apply_standard()
    689 
    690     def agg(self):

~\anaconda3\lib\site-packages\pandas\core\apply.py in apply_standard(self)
    810 
    811     def apply_standard(self):
--> 812         results, res_index = self.apply_series_generator()
    813 
    814         # wrap results

~\anaconda3\lib\site-packages\pandas\core\apply.py in apply_series_generator(self)
    826             for i, v in enumerate(series_gen):
    827                 # ignore SettingWithCopy here in case the user mutates
--> 828                 results[i] = self.f(v)
    829                 if isinstance(results[i], ABCSeries):
    830                     # If we have a view on v, we need to make a copy because

~\AppData\Local\Temp/ipykernel_10020/3744296997.py in nons(row)
      2     for i in row[['name','year_of_release']]:
      3         if row['name']=="LEGO Harry Potter: Years 5-7":
----> 4             row['year_of_release'].fillna(2012)
      5         else:
      6             continue

AttributeError: 'Timestamp' object has no attribute 'fillna'

CodePudding user response:

row['year_of_release'].astype(int).fillna(2012)

CodePudding user response:

row['year_of_release'] is a Timestamp value, it doesn't have any extra method, you can try

m1 = gaming['name'].eq('LEGO Harry Potter: Years 5-7')
m2 = gaming['year_of_release'].isna()
gaming.loc[m1 & m2 , 'year_of_release'] = 2012
# or
gaming['year_of_release'] = gaming['year_of_release'].mask(m1 & m2 , 2012)
  • Related