在按多个其他列分组的情况下,计算dataframe列中的唯一提及次数

2024-06-16 10:20:22 发布

您现在位置:Python中文网/ 问答频道 /正文

对于一个学校项目,我试图确定Reddit标题和评论中提到的具体单词的数量。更具体地说,股票行情提到。当前,数据帧如下所示(其中类型可以是标题或注释字符串):

                                                   body  score   id                    created       subreddit     type      mentions
3860  There are much better industrials stocks than ...      1  NaN  2021-03-13 20:32:08+00:00          stocks  comment          {GE}
3776  I guy I work with told me about PENN about 9 m...      1  NaN  2021-03-13 20:29:30+00:00       investing  comment        {PENN}
4122  [mp4 link](https://preview.redd.it/ieae3z7suum...      2  NaN  2021-03-13 20:28:43+00:00     StockMarket  comment          {KB}
2219     If you cant decide, then just buy $GME options      1  NaN  2021-03-13 20:28:12+00:00  wallstreetbets  comment        {GME}
2229  This sub the most wholesome fucking thing in t...      2  NaN  2021-03-13 20:27:57+00:00  wallstreetbets  comment         {GME}

其中,“提及”列包含正文中提到的一组标记(可以是多个)。我想做的是根据每种类型(评论或标题)计算每种子Reddit的独特提及次数。我期待的结果与此类似:

ticker            subreddit             type              count
 GME           wallstreetbets          comment             5
 GME           wallstreetbets           title              4
 GME             investing             comment             3
 GME             investing              title              2

重复所有提到的独特股票

我曾使用计数器来利用每个实例的特定数据帧(即一个数据帧用于wallstreetbets注释,一个数据帧用于wallstreetbets标题)来解决这个问题,但我无法找出当仅限于单个数据帧时如何使其以这种方式工作


Tags: 数据标题类型typecomment评论nanabout
1条回答
网友
1楼 · 发布于 2024-06-16 10:20:22

听起来像一个简单的groupby应该做到:

df.groupby(['mentions','subreddit','type']).count()

产生

                                        body    score   id  created
mentions    subreddit        type               
{GE}        stocks           comment    1       1       0   1
{GME}       wallstreetbets   comment    2       2       0   2
{KB}        StockMarket      comment    1       1       0   1
{PENN}      investing        comment    1       1       0   1

相关问题 更多 >