如何根据关键字的长度对Dataframe中的数字进行求和?

时间:2016-05-28 09:54:06

标签: python pandas dataframe

我有一个搜索引擎DataFrame的示例,它有2列:输入的搜索关键字和此关键字的搜索次数。 例如:

 df = pd.DataFrame({'keyword': ['one','one two','2','two 34 45', 'ab', 'long 1 4 ab'],
'number of searches': ['4', '9', '1', '2', '7', '1']})

我想总结一下对于包含1个单词,2个单词,3个单词等的关键字进行了多少次搜索(不仅仅是计算单词数),因此最终结果必须如下:

1 word: 13
2 words: 9
3 words: 2
4 words: 1

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

你可以这样做:

首先,确保您的number of searches列是整数数据类型:

df['number of searches'] = df['number of searches'].astype(int)

(df.groupby(df.keyword.str.split().apply(len))['number of searches']
   .sum()
   .to_frame()
   .reset_index()
   .apply(lambda x: '{0[0]} words: {0[1]}'.format(x), axis=1)
)

输出:

0    1 words: 12
1     2 words: 9
2     3 words: 2
3     4 words: 1
dtype: object