列表的嵌套字典到 pandas DataFrame

Nested dict of lists to pandas DataFrame

我有一个相当混乱的嵌套字典,我正试图将其转换为 pandas 数据框。数据存储在更广泛的字典中包含的列表字典中,其中每个 key/value 细分如下: {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) 对的每个主题标签的频率计数,如下所示:

+------------+------------+--------+-----+-----+------+-----+
| 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-learn 的 CountVectorizer 作为一个想法,但它无法处理嵌套字典。如果您能帮助将其转换为所需的形式,我们将不胜感激。

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