[英]Why I am getting error while using apply map function in python to replace unwanted character in header name
[英]Why am I getting error using .map in python function
我正在嘗試將字典值映射到函數中的數據集。 我不斷收到以下錯誤:
---------------------------------------------------------------------------
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')
下面是功能。 這只是在每一行上查找RATING_CLASS_CODE
,然后從字典中映射一個值,該值對應於與我的字典鍵匹配的unit_value_model
。
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)
我認為您需要具有多個條件的np.select
。
查看此答案以獲取明確的示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.