pandas json_normalize 所有列都有嵌套的字典扁平化

我有一个从非官方谷歌字典 API 返回的嵌套字典 (json)。


看起来像这样:


{'word': 'slack',

 'phonetic': '/slak/',

 'meaning': {'adjective': [{'definition': 'Not taut or held tightly in position; loose.',

    'example': 'a slack rope',

    'synonyms': ['loose',

     'limp',

     'not taut',

     'not tight',

     'hanging',

     'flapping']},

   {'definition': '(of business) characterized by a lack of work or activity; quiet.',

    'example': 'business was rather slack'},

   {'definition': 'Having or showing laziness or negligence.',

    'example': 'slack accounting procedures',

    'synonyms': ['lax',

     'negligent',

     'neglectful',

     'remiss',

     'careless',

     'slapdash',

     'slipshod',

     'lackadaisical',

     'lazy',

     'inefficient',

     'incompetent',

     'inattentive',

     'offhand',

     'casual',

     'disorderly',

     'disorganized']},

   {'definition': '(of a tide) neither ebbing nor flowing.',

    'example': 'soon the water will become slack, and the tide will turn'}],

  'noun': [{'definition': 'The part of a rope or line which is not held taut; the loose or unused part.',

    'example': 'I picked up the rod and wound in the slack',

    'synonyms': ['looseness', 'play', 'give']},

   {'definition': 'Casual trousers.'},

   {'definition': 'A spell of inactivity or laziness.',

    'example': 'he slept deeply, refreshed by a little slack in the daily routine',

    'synonyms': ['lull',

     'pause',

     'respite',

     'spell of inactivity',

     'interval',

     'break',

     'hiatus',

     'breathing space']}],


现在,字典 j 有三个键。


j.keys() # dict_keys(['word', 'phonetic', 'meaning'])

我主要对含义感兴趣:


j['meaning'].keys() # dict_keys(['adjective', 'noun', 'verb', 'adverb'])

为了获取熊猫数据框,我使用了以下代码:


json_normalize(data=j['meaning'])

这给出了一个只有 4 列的数据框。


在这里,每个词性(形容词、名词等)都必须有“定义”键,“示例”和“同义词”是可选的。


j['meaning']['adjective'][0].keys() # dict_keys(['definition', 'example', 'synonyms'])

如何获取 4 * 3 = 12 列的数据框,列名像adjective_definition, adjective_example, ...., verb_synonyms?


慕妹3242003
浏览 307回答 3
3回答

四季花海

有点凌乱的解决方案,但我认为它有效。从j作为示例字典开始:res = pd.concat([json_normalize(v, meta=['definition', 'example', 'synonyms']).add_prefix(k + '_')                 for k, v in j['meaning'].items()],                 axis=1)# The output is super wide and hard to read in console output,# but hopefully this confirms the output is (close to) what you needres                                                adjective_definition  \0                       Not taut or held tightly in position; loose.   1  (of business) characterized by a lack of work or activity; quiet.   2                          Having or showing laziness or negligence.   3                            (of a tide) neither ebbing nor flowing.                                             adjective_example  \0                                              a slack rope   1                                 business was rather slack   2                               slack accounting procedures   3  soon the water will become slack, and the tide will turn                                                                   adjective_synonyms  \0                            [loose, limp, not taut, not tight, hanging, flapping]   1                                                                              NaN   2  [lax, negligent, neglectful, remiss, careless, slapdash, slipshod, lackadais...   3                                                                              NaN                                                                   noun_definition  \0  The part of a rope or line which is not held taut; the loose or unused part.   1                                                              Casual trousers.   2                                            A spell of inactivity or laziness.   3                                                                           NaN                                                           noun_example  \0                         I picked up the rod and wound in the slack   1                                                                NaN   2  he slept deeply, refreshed by a little slack in the daily routine   3                                                                NaN                                                                        noun_synonyms  \0                                                          [looseness, play, give]   1                                                                              NaN   2  [lull, pause, respite, spell of inactivity, interval, break, hiatus, breathi...   3                                                                              NaN                                           verb_definition  \0                Loosen (something, especially a rope).   1  Decrease or reduce in intensity, quantity, or speed.   2                                Work slowly or lazily.   3                                         Slake (lime).                                         verb_example  \0                                              NaN   1                    the flow of blood slacked off   2  she reprimanded her girls if they were slacking   3                                              NaN                                                                        verb_synonyms  \0                                                                              NaN   1                               [reduce, lessen, slacken, slow, ease off, ease up]   2  [idle, shirk, be inactive, be lazy, be indolent, sit back and do nothing, wa...   3                                                                              NaN     adverb_definition                                          adverb_example  0          Loosely.  their heads were hanging slack in attitudes of despair  1               NaN                                                     NaN  2               NaN                                                     NaN  3               NaN                                                     NaN  
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python