嵌套列表到数据帧的dict

2024-09-28 21:02:46 发布

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

我有一个相当混乱的嵌套字典,我正试图转换成熊猫数据帧。数据存储在更广泛的字典中的列表字典中,每个键/值细分如下: {userID_key: {postID_key: [list of hash tags]}}

下面是一个更具体的数据示例:

   {'user_1': {'postID_1':  ['#fitfam',
                             '#gym',
                             '#bro'],
               'postID_2':  ['#swol',
                             '#anotherhashtag']},
    'user_2': {'postID_78': ['#ripped',
                             '#bro',
                             '#morehashtags'],
               'postID_1':  ['#buff',
                             '#othertags']},
    'user_3': ...and so on }

我想创建一个数据帧,为每个(userID,postID)对提供每个hashtag的频率计数,如下所示:

+------------+------------+--------+-----+-----+------+-----+
| UserID_key | PostID_key | fitfam | gym | bro | swol | ... |
+------------+------------+--------+-----+-----+------+-----+
| user_1     | postID_1   | 1      | 1   | 1   | 0    | ... |
| user_1     | postID_2   | 0      | 0   | 0   | 1    | ... |
| user_2     | postID_78  | 0      | 0   | 1   | 0    | ... |
| user_2     | postID_1   | 0      | 0   | 0   | 0    | ... |
| user_3     | ...        | ...    | ... | ... | ...  | ... |
+------------+------------+--------+-----+-----+------+-----+

我把scikit学习的CountVectorizer作为一个想法,但它不能处理嵌套字典。如果你能帮我把它做成你想要的样子,我将不胜感激。你知道吗


Tags: of数据key列表字典list细分gym
1条回答
网友
1楼 · 发布于 2024-09-28 21:02:46

my answer to another question的基础上,可以使用pd.concat构建和连接子帧,然后使用stackget_dummies

(pd.concat({k: pd.DataFrame.from_dict(v, orient='index') for k, v in dct.items()})
   .stack()
   .str.get_dummies()
   .sum(level=[0, 1]))

                  #anotherhashtag  #bro  #buff  #fitfam  #gym  #morehashtags  #othertags  #ripped  #swol
user_1 postID_1                 0     1      0        1     1              0           0        0      0
       postID_2                 1     0      0        0     0              0           0        0      1
user_2 postID_78                0     1      0        0     0              1           0        1      0
       postID_1                 0     0      1        0     0              0           1        0      0

相关问题 更多 >