1
votes

Transformer un Dict imbriqué dans un dataframe?

J'ai essayé d'analyser le dict imbriqué dans le bloc de données. J'ai créé ce df à partir de dict, mais je n'ai pas pu trouver celui imbriqué.

df

   'archi': [{'fourth': '115',
      'fifth': '-162',
      'sixth': '112'},
     {'fourth': '52',
      'fifth': '42',
      'sixth': ' 32'}]

dict imbriqué:

        First   second  fourth   fifth   sixth   fourth   fifth   sixth          

 0     1       2       4         5        6         7       8       9


0 commentaires

3 Réponses :


1
votes

Je ne peux pas quitter le format du dict imbriqué dans la "troisième" colonne, mais voici ce que je recommande d'utiliser Python: Pandas dataframe from Series of dict comme point de départ. Voici un dict et un dataframe qui sont reproductibles:

df.thrd_1 = df.third.apply(lambda x: x['archi']) # convert to list
df.thrd_1a = df.thrd_1.apply(lambda x: x[0]) # access first item
df.thrd_1b = df.thrd_1.apply(lambda x: x[1]) # access second item

out = df.drop('third', axis=1).merge(
    df.thrd_1a.apply(pd.Series).merge(df.thrd_1a.apply(pd.Series),
    left_index=True, right_index=True),
    left_index=True, right_index=True)

print(out)

First  Second fourth_x fifth_x sixth_x fourth_y fifth_y sixth_y
0      1       2      115    -162     112      115    -162     112
1      2       3      115    -162     112      115    -162     112

Ensuite, vous devez d'abord accéder à la liste dans le dict, puis aux éléments de la liste:

nst_dict = {'archi': [{'fourth': '115', 'fifth': '-162', 'sixth': '112'},
      {'fourth': '52', 'fifth': '42','sixth': ' 32'}]}

df = pd.DataFrame.from_dict({'First':[1,2], 'Second':[2,3], 
     'third': [nst_dict,nst_dict]})


0 commentaires

0
votes

Une approche "force brute"

     Zero   First   Second   fourth     fifth   sixth   fourth  fifth   sixth
0       0       1        2      115      -162     112      52      42      32

Résultat:

import pandas as pd
import numpy as np

my_dict = {'Zero': 0, 'First': 1, 'Second': 2,
       'archi': [{'fourth': '115', 'fifth': '-162', 'sixth': '112'},
                {'fourth': '52', 'fifth': '42', 'sixth': ' 32'}]}

data_row=[]
columns = []
for key in my_dict.keys():
    try:
        if len(my_dict[key]):
            for item in my_dict[key]:
                # iterate over nested dicts
                for k, v in item.items():
                    columns.append(k)
                    data_row.append(v)

    except TypeError:
        data_row.append(my_dict[key])
        columns.append(key)

print(columns)
print(data_row)

data = np.array(data_row).reshape(1,9)
df = pd.DataFrame(new_d, columns=columns)
print(df)


0 commentaires

0
votes

J'ai créé une fonction en utilisant une approche récursive pour aplatir la structure du dict:

pd.DataFrame(flattened_dict)

Puis la création du dataframe:

original_dict = {'Zero': 0, 'First': 1, 'Second': 2,
       'archi': [{'fourth': '115', 'fifth': '-162', 'sixth': '112'},
                {'fourth': '52', 'fifth': '42', 'sixth': ' 32'}]}

flattened_dict = {}

def flatten(obj, name = ''):
    if isinstance(obj, dict):
        for key, value in obj.items():
            flatten(obj[key], key)
    elif isinstance(obj, list):
        for e in obj:
            flatten(e)
    else:
        flattened_dict[name] = [obj] 

flatten(original_dict)

Avec la sortie suivante:

 entrez la description de l'image ici


0 commentaires