如何以正确的方式应用此函数?

2024-06-01 02:17:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理我找到的数据集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().

你想帮我吗

谢谢,, 乔瓦尼


Tags: nameinselfdfreturndefboroughvalueerror
3条回答

如果您有一个大的df,那么不值得使用apply方法。 相反,您可以使用map方法,如下所示:

# define your dictionary
num_to_name = {'1': 'Manhattan', '2': 'Bronx', '3': 'Brooklyn', '4': 'Queens'}
# map the values in BOROUGH column
df['BOROUGH'] = df['BOROUGH'].map(num_to_name)

你可以做:

df['BOROUGH'] = df['BOROUGH'].apply(name_boro)

您可以使用map,但使用默认值。顺便说一句,您不需要将原始数字转换为字符串

df.BOROUGH.map(lambda x: {1: 'Manhattan', 2: 'Bronx', 3: 'Brooklyn', 4: 'Queens'}.get(x, 'Staten Island'))

相关问题 更多 >