使用应用函数时,如何修复类型错误?

问题描述 投票:1回答: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))

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

python dataframe apply
1个回答
0
投票

你犯了一个小错误!在应用时,数据框架的名称是错误的!!!!!!。

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))
© www.soinside.com 2019 - 2024. All rights reserved.