【问题标题】:How to fix the type error when using the apply function使用apply函数时如何修复类型错误
【发布时间】:2020-05-23 05:53:08
【问题描述】:

我正在尝试对表中的列使用 apply 函数。这是示例数据和代码。

df = pd.DataFrame({'a':[0,1,2], 'text':["I love a dog", "He is smart", "I hate this"]})

def edit(input_text):
    output = input_text[:4]
    return output


df['text'].apply(lambda x: edit(x))

我以为它会对该列中的每一行应用编辑功能,但它给了我类型错误。

【问题讨论】:

  • 代码对我有用
  • 能否请您在帖子中也添加错误?
  • 您的代码在我的机器上运行良好,请显示详细信息错误
  • 代码对我来说工作正常
  • 我认为您正在使用 df_train 作为 apply 函数。我想你应该使用df

标签: python pandas dataframe apply


【解决方案1】:

你犯了一个小错误!申请时数据框名称错误!!!

df = pd.DataFrame({'a':[0,1,2], 'text':["I love a dog", "He is smart", "I hate this"]})

def edit(input_text):
    output = input_text[:4]
    return output

df['text'].apply(lambda x: edit(x))

【讨论】:

  • 不错的收获哈哈,但这只是我发帖时的错误。实际代码具有正确的 df 名称。并给了我类型错误
  • 使用 df_train 代替 df 不会引发“类型错误”,而是会引发“名称错误”。我认为这是发布时的拼写错误
猜你喜欢
  • 1970-01-01
  • 2022-07-27
  • 1970-01-01
  • 1970-01-01
  • 2021-11-17
  • 2021-06-23
  • 2021-09-24
  • 1970-01-01
  • 2019-10-07
相关资源
最近更新 更多