[SOLVED] Why am I getting error using .map in python function

Issue

I’m trying to map a dictionary value to a dataset in a fuction. I keep getting the following error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-114-f1360d45f8fc> in <module>
----> 1 df['unit_value_factor_4'] = df.apply(map_value, axis=1)

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\frame.py in apply(self, func, axis, broadcast, raw, reduce, result_type, args, **kwds)
   6012                          args=args,
   6013                          kwds=kwds)
-> 6014         return op.get_result()
   6015 
   6016     def applymap(self, func):

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\apply.py in get_result(self)
    140             return self.apply_raw()
    141 
--> 142         return self.apply_standard()
    143 
    144     def apply_empty_result(self):

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\apply.py in apply_standard(self)
    246 
    247         # compute the result using the series generator
--> 248         self.apply_series_generator()
    249 
    250         # wrap results

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\apply.py in apply_series_generator(self)
    275             try:
    276                 for i, v in enumerate(series_gen):
--> 277                     results[i] = self.f(v)
    278                     keys.append(v.name)
    279             except Exception as e:

<ipython-input-113-2ec7fc46c34e> in map_value(row)
      2 def map_value(row):
      3     if row['RATING_CLASS_CODE'] == 'G':
----> 4         val = row['unit_value_model'].map(g_cn_value)
      5 
      6     elif row['RATING_CLASS_CODE'] == 'CN':

AttributeError: ("'float' object has no attribute 'map'", 'occurred at index 40')

Below is the function. This is simply looking up the RATING_CLASS_CODE on each row, then mapping a value from a dictionary that corresponds to the unit_value_model which matches my dictionary key.

def map_value(row):
    if row['RATING_CLASS_CODE'] == 'G':
        val = row['unit_value_model'].map(g_cn_value)

    elif row['RATING_CLASS_CODE'] == 'CN':
        val = row['unit_value_model'].map(g_cn_value)

    elif row['RATING_CLASS_CODE'] == 'NE':
        val = row['unit_value_model'].map(ne_gv_value)

    elif row['RATING_CLASS_CODE'] == 'GV':
        val = row['unit_value_model'].map(ne_gv_value)

    elif row['RATING_CLASS_CODE'] == 'LA':
        val = row['unit_value_model'].map(la_coll_value)

    else:
        val = None

        print(val)

        return val

df['unit_value_factor_4'] = df.apply(map_value, axis=1)

Solution

I thnk you need np.select with multiple conditions.

Look at this answer for an explicit example.

Answered By – Erfan

Answer Checked By – Senaida (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.