Pandas sum of all word counts in column

前端 未结 4 1093
自闭症患者
自闭症患者 2021-01-23 21:03

I have a pandas column that contains strings. I want to get a word count of all of the words in the entire column. What\'s the best way of doing that without looping through eac

4条回答
  •  别那么骄傲
    2021-01-23 21:19

    You could use the vectorized string operations:

    In [7]: df["a"].str.split().str.len().sum()
    Out[7]: 6
    

    which comes from

    In [8]: df["a"].str.split()
    Out[8]: 
    0          [some, words]
    1    [lots, more, words]
    2                   [hi]
    Name: a, dtype: object
    
    In [9]: df["a"].str.split().str.len()
    Out[9]: 
    0    2
    1    3
    2    1
    Name: a, dtype: int64
    
    In [10]: df["a"].str.split().str.len().sum()
    Out[10]: 6
    

提交回复
热议问题