【发布时间】: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.tokenize 的sent_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
我已确认每一行都有 dtype 和 str。也许是因为description 有dtype('O')?
我在这里做错了什么?在这里使用带有自定义函数的 pipe 可以正常工作,但我更喜欢使用 assign。
【问题讨论】:
标签: python pandas lambda assign