【问题标题】:How can I apply this function in a correct way?如何以正确的方式应用此功能?
【发布时间】:2021-08-24 21:39:07
【问题描述】:

我正在处理我找到的数据集here。

我尝试编写一个函数来将 BOROUGH 列的每个值从数字转换为名称。 像这样:

# 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(最近一次调用 最后)在 19 返回“史坦顿岛” 20 ---> 21 df.apply(name_boro(df['BOROUGH']))

in name_boro(s) 8 9 def name_boro(s): ---> 10 如果 s == '1': 11 返回“曼哈顿” 12 elif s == '2':

~\anaconda3\lib\site-packages\pandas\core\generic.py 在 非零(自我)1327 1328 def 非零(自我): -> 1329 raise ValueError( 1330 f"{type(self).name} 的真值不明确。" 1331
“使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。”

ValueError:Series 的真值不明确。使用a.empty, a.bool()、a.item()、a.any() 或 a.all()。

愿意帮助我吗?

谢谢你, 乔瓦尼

【问题讨论】:

    标签: python pandas dataframe jupyter-notebook


    【解决方案1】:

    如果您的 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)
    

    【讨论】:

    • 这个map 方法可能比使用带有自定义函数的apply 运行得更快是正确的,尤其是对于大型数据集。所以最好保留强调这一点。无论如何都赞成。
    【解决方案2】:

    你可以这样做:

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-07-03
        • 1970-01-01
        • 1970-01-01
        • 2021-12-30
        • 1970-01-01
        • 1970-01-01
        • 2014-03-06
        相关资源
        最近更新 更多