使用pandas groupby查找每个组中文本的平均长度

时间:2017-11-23 16:24:22

标签: python pandas pandas-groupby

我使用的是莎士比亚语料库。

    act literature_type scene   scene_text  scene_title speaker title
0   1   Comedy  1   In delivering my son from me, I bury a second ...   Rousillon. The COUNT's palace.  COUNTESS    All's Well That Ends Well
1   1   Comedy  1   And I in going, madam, weep o'er my father's d...   Rousillon. The COUNT's palace.  BERTRAM All's Well That Ends Well
2   1   Comedy  1   You shall find of the king a husband, madam; y...   Rousillon. The COUNT's palace.  LAFEU   All's Well That Ends Well
3   1   Comedy  1   What hope is there of his majesty's amendment?  Rousillon. The COUNT's palace.  COUNTESS    All's Well That Ends Well
4   1   Comedy  1   He hath abandoned his physicians, madam; under...   Rousillon. The COUNT's palace.  LAFEU   All's Well That Ends Well

我想找到每个标题的平均scene_text长度。

我想要使用以下内容:

all_works_by_speaker_df.groupby('title').apply(lambda x: np.mean(len(x)))

这只返回每个标题中的场景数。

2 个答案:

答案 0 :(得分:5)

如果需要len个字符:

df = (all_works_by_speaker_df.groupby('title')['scene_text']
                            .apply(lambda x: np.mean(x.str.len()))
                            .reset_index(name='mean_len_text'))
print (df)

                       title  mean_len_text
0  All's Well That Ends Well           48.4

如果需要len个单词,请使用Vaishali's solution

答案 1 :(得分:2)

Split,len和mean

df.groupby('title').scene_text.apply(lambda x: x.str.split().str.len().mean())


title
All's Well That Ends Well    9.2