我正在处理我找到的数据集here
我试图编写一个函数,将列区域的每个值从数字转换为名称。 像这样:
# Manhattan (1), Bronx (2), Brooklyn (3), Queens (4), and Staten Island (5)
## convert BOROUGHS from int to string
df['BOROUGH'] = df['BOROUGH'].astype(str)
## create a function to replace number with name
def name_boro(s):
if s == '1':
return 'Manhattan'
elif s == '2':
return 'Bronx'
elif s == '3':
return 'Brooklyn'
elif s == '4':
return 'Queens'
else:
return 'Staten Island'
df.apply(name_boro(df['BOROUGH']))
输出消息如下:
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) in 19 return 'Staten Island' 20 ---> 21 df.apply(name_boro(df['BOROUGH']))
in name_boro(s) 8 9 def name_boro(s): ---> 10 if s == '1': 11 return 'Manhattan' 12 elif s == '2':
~\anaconda3\lib\site-packages\pandas\core\generic.py in nonzero(self) 1327 1328 def nonzero(self): -> 1329 raise ValueError( 1330 f"The truth value of a {type(self).name} is ambiguous. " 1331
"Use a.empty, a.bool(), a.item(), a.any() or a.all()."ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
你想帮我吗
谢谢,, 乔瓦尼
如果您有一个大的df,那么不值得使用
apply
方法。 相反,您可以使用map
方法,如下所示:你可以做:
您可以使用
map
,但使用默认值。顺便说一句,您不需要将原始数字转换为字符串相关问题 更多 >
编程相关推荐