Pandas:如何创建数据框中出现的元素的频率分布

Pandas: How to Create Frequency Distribution of Elements Ocurring in Dataframe

我有一个包含三列的 Pandas 数据框:句子、关键短语、类别。 关键短语列包含空列表或它来自的句子行中的 words/phrases,如下所示:

Sentence Key Phrases Category
the red ball ['red ball'] object
a big blue box ['blue'] object
he throws the red ball ['he throws','red ball'] action

我想检查整个 关键短语 列的内容,并为每个独特的短语构建一个频率字典(或任何最好的)。所以在我的例子中,我会有类似的东西:'red ball': 2, 'blue': 1, 'he throws': 1

然后我想计算这些关键短语在数据框中所有类别中的频率分布。所以在我的例子中,object 类别是 'blue' 的 100%,但只有 50% 的 'red ball'。我假设最好的方法是从我上面提到的频率字典开始?

最后,我想向数据框添加另一列,该列将针对其行中的每个关键短语显示该类别中该关键短语出现的百分比。

所以最终的 DF 看起来像这样,但只要信息存在,美学并不重要:

Sentence Key Phrases Category Key Phrase Ocurrences
the red ball ['red ball'] object red ball: 50%
a big blue box ['blue'] object blue: 100%
he throws the red ball ['he throws', 'red ball'] action he throws: 100%, red ball: 50%

拥有像字典之类的东西也很有用,其中每个键都是类别,每个值包含该类别中出现的所有关键短语及其流行度,所以也许这会在我的初始字典中创建?

你可以试试

df['Key Phrase Ocurrences'] = 100 * df.nunique(axis = 1)/df.count(axis = 1)

首先我们展开 df,所以我们有一行一行的关键短语:

df2 = df.explode('Key Phrases')
df2

输出:


    Sentence                Key Phrases Category
0   the red ball            red ball    object
1   a big blue box          blue        object
2   he throws the red ball  he throws   action
2   he throws the red ball  red ball    action

然后我们创建 table 个事件:

df3 = df2.groupby(['Key Phrases','Category'])['Sentence'].count().unstack().fillna(0)
df3

输出:

Category    action  object
Key Phrases     
blue        0.0     1.0
he throws   1.0     0.0
red ball    1.0     1.0

然后我们通过将出现次数除以总数来转换为频率

df4 = df3.apply(lambda c: c/df3.sum(axis=1))
df4

输出:


Category    action  object
Key Phrases     
blue        0.0     1.0
he throws   1.0     0.0
red ball    0.5     0.5

这回答了您问题的第 1 部分

为了将其拟合回原始数据,我们可以执行以下操作。对已经分解的版本,数据框 df2:

做起来更容易
df2.merge(df4.unstack().rename('freq').reset_index(), how = 'left', on = ['Category', 'Key Phrases'])

输出:

    Sentence                Key Phrases    Category      freq
--  ----------------------  -------------  ----------  ------
 0  the red ball            red ball       object         0.5
 1  a big blue box          blue           object         1
 2  he throws the red ball  he throws      action         1
 3  he throws the red ball  red ball       action         0.5

这里有您希望看到的所有信息,但诚然格式不是很漂亮。正如你所说,格式并不重要,我会把它留在这里,但你总是可以做更多 groupbys etc