将数据帧转换为 Python 中的矩阵以用于标签集

Transform dataframes into matrix in Python for hashtag sets

这是我的数据集 'new.csv'。另外我post这里一目了然:

https://drive.google.com/file/d/17xbwgp9siPuWsPBN5rUL9VSYwl7eU0ca/view?usp=sharing

    Dominant_Topic  Hashtags
0       4.0         [#boycottmulan, #blacklivesmatter]
1       8.0         []
2       8.0         [#blacklivesmatter, #protests]
3       4.0         [#blacklivesmatter, #swoleinsolidarity]
4       4.0         [#starlink]
... ... ...
15995   4.0         [#verizon5gaccess, #oscars, #verizon5gaccess, #sweepstakes, #glennclose]
15996   5.0         [#blacklivesmatter, #lifewithkellykhumalo, #bushiri, #vodacomnxtlvl, #amakhosi4life]
15997   8.0         [#blm, #blacklivesmatter, #trumpkillsamericans]
15998   3.0         [#tmobiletrucks, #str, #allin, #tmogoeslocal]
15999   0.0         [#tdcsvm, #officialtdcent, #dmv, #blacklivesmatter, #fox5dc]

我的目标是删除数据集中少于 80 次的所有主题标签计数 'new' 并使用其余主题标签形成矩阵(来自第 4 列),如下所示:

如您所见,从第 4 列开始,它开始编码 1 或 0,以指示给定主题标签(在数据集中出现超过 80 次的剩余主题标签)是否存在于“Hashtags”列中

我做了一个哈希值如下:

hashtags_list_new = new.loc[new.Hashtags.apply(lambda hashtags_list:hashtags_list !=[]),['Hashtags']]

# which hashtags were popular? 
# create dataframe where each use of hashtag gets its own row
flattened_hashtags_new = pd.DataFrame([hashtag for hashtags_list in hashtags_list_new.Hashtags for hashtag in hashtags_list],columns=['Hashtags'])

# count of appearances of each hashtag
popular_hashtags_new =flattened_hashtags_new.groupby('Hashtags').size().reset_index(name='counts')\
                                  .sort_values('counts',ascending=False)\
                                    .reset_index(drop=True)
popular_hashtags_new

结果是:

        Hashtags            counts
0       #blacklivesmatter   11379
1       #blm                1022
2       #jacobblake         565
3       #verizon5gaccess    510
4       #sweepstakes        496
... ... ...
1484    #idolportraits      11
1485    #augmentedreality   11
1486    #smartphones        11
1487    #ar                 11
1488    #cx                 11

但我不知道如何获得我的目标。任何人都可以帮我解决吗?谢谢关注。

你能检查一下这是否符合你的需要吗(我假设你的基础数据框被命名为 new):

from collections import Counter

counts = new.Hashtags.map(Counter).sum().most_common(80)
top_hashtags = [ht for ht, _ in counts]
hashtags = new.Hashtags.map(set)
base_cols = ['Dominant_Topic', 'Hashtags']
matrix = pd.concat(
             [new[base_cols]] +
             [
                 hashtags.map(lambda hts: ht in hts).astype(int)
                 for ht in top_hashtags
             ],
             axis='columns'
         )
matrix.columns = base_cols + top_hashtags

我正在使用 Counter 及其方法 most_common 到 select 前 80 个主题标签 (counts),然后 select 键生成前 80 个标签的排序列表 (top_hashtags)。然后我将 new.Hashtag 中的列表转换为集合 (hashtags),因为集合的成员资格测试效率更高。之后,我为每个热门标签创建一个 0/​​1 系列,指示此标签是否存在于 new.Hashtag 中的相应列表中,将它们全部连接起来,包括开头的 new 数据框,并命名结果 matrix.