如何使用 pandas 计算 python 中的字数

how to count word numbers in python using pandas

我有一个 csv 文件,其中包含 2 列,名为“单词”和“频率”,并且想要 return 频率为 2 或更少的单词数的总和,这是我正在尝试使用的代码,但是它说

TypeError: unsupported operand type(s) for +: 'int' and 'str'

df=pd.read_csv('dictionary.csv')

result=(sum(df['word'] if df['freq']<=2))
print("the number of words appearing  less than 3 times are :{}".format{reslt})

数据样本

如果要统计符合条件的行数,那么表示mask的True个数只用sum:

result = (df['freq']<=2).sum()

或者:

result = df['freq'].le(2).sum()