Count number of words per row

后端 未结 4 1023
既然无缘
既然无缘 2020-11-29 08:32

I\'m trying to create a new column in a dataframe that contains the word count for the respective row. I\'m looking to the total number of words, not frequencies of each di

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-29 09:03

    This is one way using pd.Series.str.split and pd.Series.map:

    df['word_count'] = df['col'].str.split().map(len)
    

    The above assumes that df['col'] is a series of strings.

    Example:

    df = pd.DataFrame({'col': ['This is an example', 'This is another', 'A third']})
    
    df['word_count'] = df['col'].str.split().map(len)
    
    print(df)
    
    #                   col  word_count
    # 0  This is an example           4
    # 1     This is another           3
    # 2             A third           2
    

提交回复
热议问题