我有一个包含 2 列的数据框 (df_cluster) [客户 ID,集群]。大约有 13 个集群,我尝试使用 python 中的 apply() 为每个集群分配一个名称。我过去使用过相同的函数并且工作正常,但现在我收到“UnboundLocalError”错误。
如果我做错了什么,请告诉我。我对 apply() 的理解是,它跨轴传递函数(在这种情况下,函数 cluster_name 将为每一行传递)
这是代码
def cluster_name(df):
if df['cluster'] == 1:
value = 'A'
elif df['cluster'] == 2:
value = 'B'
elif df['cluster'] == 3:
value = 'C'
elif df['cluster'] == 4:
value = 'D'
elif df['cluster'] == 5:
value = 'E'
elif df['cluster'] == 6:
value = 'F'
elif df['cluster'] == 7:
value = 'G'
return value
df_cluster['cluster_name'] = df_cluster.apply(cluster_name, axis = 1)
错误
UnboundLocalError Traceback (most recent call last)
<ipython-input-16-b64f3fdc1260> in <module>
16 return value
17
---> 18 df_cluster['cluster_name'] = df_cluster.apply(cluster_name, axis = 1)
19 df_cluster['cluster_name'].value_counts()
/opt/cloudera/parcels/Anaconda/envs/py36/lib/python3.6/site-packages/pandas/core/frame.py in apply(self, func, axis, broadcast, raw, reduce, result_type, args, **kwds)
6926 kwds=kwds,
6927 )
-> 6928 return op.get_result()
6929
6930 def applymap(self, func):
/opt/cloudera/parcels/Anaconda/envs/py36/lib/python3.6/site-packages/pandas/core/apply.py in get_result(self)
184 return self.apply_raw()
185
--> 186 return self.apply_standard()
187
188 def apply_empty_result(self):
MYYA
catspeake
白衣染霜花