【问题标题】:How to solve Python Pandas assign error when creating new column创建新列时如何解决Python Pandas分配错误
【发布时间】:2021-12-30 23:04:04
【问题描述】:

我有一个包含家庭描述的数据框:

description
0   Beautiful, spacious skylit studio in the heart...
1   Enjoy 500 s.f. top floor in 1899 brownstone, w...
2   The spaceHELLO EVERYONE AND THANKS FOR VISITIN...
3   We welcome you to stay in our lovely 2 br dupl...
4   Please don’t expect the luxury here just a bas...
5   Our best guests are seeking a safe, clean, spa...
6   Beautiful house, gorgeous garden, patio, cozy ...
7   Comfortable studio apartment with super comfor...
8   A charming month-to-month home away from home ...
9   Beautiful peaceful healthy homeThe spaceHome i...

我正在尝试计算每行上的句子数(使用来自nltk.tokenizesent_tokenize)并将这些值作为新列sentence_count 附加到df。由于这是更大数据管道的一部分,因此我使用 pandas assign 以便可以链接操作。

不过,我似乎无法让它工作。我试过了:

df.assign(sentence_count=lambda x: len(sent_tokenize(x['description'])))

df.assign(sentence_count=len(sent_tokenize(df['description'])))

但两者都会引发以下错误:

TypeError: expected string or bytes-like object

我已确认每一行都有 dtypestr。也许是因为descriptiondtype('O')

我在这里做错了什么?在这里使用带有自定义函数的 pipe 可以正常工作,但我更喜欢使用 assign

【问题讨论】:

    标签: python pandas lambda assign


    【解决方案1】:

    x['description'] 在第一个示例中传递给sent_tokenize 时是pandas.Series。它不是一个字符串。它是一个字符串系列(类似于列表)。

    所以你应该这样做:

    df.assign(sentence_count=df['description'].apply(sent_tokenize))
    

    或者,如果您需要将额外的参数传递给sent_tokenize

    df.assign(sentence_count=df['description'].apply(lambda x: sent_tokenize(x)))
    

    【讨论】:

    • 最初就是这样做的,但我正在寻找一种在没有df['counts'] = 的情况下链接sent_tokenize 的方法。有没有办法让它成为链式操作的一部分?
    • 是的!有。我没有意识到这就是你试图用df.assign 做的事情:) 现在检查答案。
    • 太好了,谢谢!对于未来的读者来说只有一件事:我认为x['description'] 应该是df['description']。否则会出错
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-06
    • 2020-07-30
    • 1970-01-01
    • 2021-11-03
    相关资源
    最近更新 更多