【问题标题】:Getting the length of text in a dataframe in python在python中获取数据框中的文本长度
【发布时间】:2020-07-27 17:33:50
【问题描述】:

所以我有这个数据框:

    Text                                             target
    #Coronavirus is a cover for something else. #5...   D
    Crush the One Belt One Road !! \r\n#onebeltonf...   B
    RT @nickmyer: It seems to be, #COVID-19 aka #c...   B
    @Jerusalem_Post All he knows is how to destroy...   B
    @newscomauHQ Its gonna show us all. We will al...   B

文本是推文,我试图获取文本列中每个字符串的计数并将计数输入到数据框中。我已经尝试过这个

d = pd.read_csv('5gCoronaFinal.csv')
d['textlength'] = [len(int(t)) for t in d['Text']]

但它一直给我这个错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-42-dabcab1de7b2> in <module>
----> 1 d['textlength'] = [len(t) for t in d['Text']]

<ipython-input-42-dabcab1de7b2> in <listcomp>(.0)
----> 1 d['textlength'] = [len(t) for t in d['Text']]

TypeError: object of type 'float' has no len()

我试过像这样将 t 转换为整数:

d['textlength'] = [len(int(t)) for t in d['Text']]

但是它给了我这个错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-43-9ae56e5f7912> in <module>
----> 1 d['textlength'] = [len(int(t)) for t in d['Text']]

<ipython-input-43-9ae56e5f7912> in <listcomp>(.0)
----> 1 d['textlength'] = [len(int(t)) for t in d['Text']]

ValueError: invalid literal for int() with base 10: '#Coronavirus is a cover for something else. #5g is being rolled out and they are expecting lots to...what? Die from #60ghz +. They look like they are to keep the cold in? #socialdistancing #covid19 #

我需要一些帮助谢谢!

【问题讨论】:

标签: python pandas dataframe


【解决方案1】:

您可以使用str 访问器进行向量化字符串操作。在这种情况下,您可以使用str.splitstr.len

df['Text_length'] = df.Text.str.split().str.len()

print(df)

                                                Text target  Text_length
0  #Coronavirus is a cover for something else. #5...      D            8
1  Crush the One Belt One Road !! \r\n#onebeltonf...      B            8
2      RT @nickmyer: It seems to be, #COVID-19 aka #      B            9
3     @Jerusalem_Post All he knows is how to destroy      B            8
4     @newscomauHQ Its gonna show us all. We will al      B            9

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    • 2018-10-24
    相关资源
    最近更新 更多