Explodieren Sie verschachtelte JSON zum DataFramePython

Python-Programme
Anonymous
 Explodieren Sie verschachtelte JSON zum DataFrame

Post by Anonymous »

Es gibt viele Antworten zu diesem Thema, aber für mein Leben kann ich keine Lösung für mein Problem haben.

Code: Select all

json_2_explode = [{'scalar': '43',
'units': 'm',
'parameter': [{'no_1': '45',
'no_2': '1038',
'no_3': '356'}],
'name': 'Foo'},
{'scalar': '54.1',
'units': 's',
'parameter': [{'no_1': '78',
'no_2': '103',
'no_3': '356'}],
'name': 'Yoo'},
{'scalar': '1123.1',
'units': 'Hz',
'parameter': [{'no_1': '21',
'no_2': '43',
'no_3': '3577'}],
'name': 'Baz'}]
Dokumentieren Sie einige Lesungen für Attribute Foo , yoo und baz . Für jedes Ich detaillierte eine Nummer, dh den Wert selbst, einige Parameter und den Namen.

Code: Select all

df = pd.DataFrame(data = {'col1': [11, 9, 23, 1],
'col2': [7, 3, 1, 12],
'col_json' : [json_2_explode,
json_2_explode,
json_2_explode,
json_2_explode]}, index=[0, 1, 2, 3])
< /code>
    col1    col2    col_json
0   11      7        [{'scalar': '43', 'units': 'MPa', 'parameter':...
1   9       3        [{'scalar': '43', 'units': 'MPa', 'parameter':...
2   23      1        [{'scalar': '43', 'units': 'MPa', 'parameter':...
3   1       12       [{'scalar': '43', 'units': 'MPa', 'parameter':...
< /code>
The issue I have is that if I try
df = pd.json_normalize(df['col_json'].explode())
< /code>
I get
    scalar  units            parameter                          name
0   43      m   [{'no_1': '45', 'no_2': '1038', 'no_3': '356'}] Foo
1   54.1    s   [{'no_1': '78', 'no_2': '103', 'no_3': '356'}]  Yoo
2   1123.1  Hz  [{'no_1': '21', 'no_2': '43', 'no_3': '3577'}]  Baz
3   43      m   [{'no_1': '45', 'no_2': '1038', 'no_3': '356'}] Foo
4   54.1    s   [{'no_1': '78', 'no_2': '103', 'no_3': '356'}]  Yoo
5   1123.1  Hz  [{'no_1': '21', 'no_2': '43', 'no_3': '3577'}]  Baz
6   43      m   [{'no_1': '45', 'no_2': '1038', 'no_3': '356'}] Foo
7   54.1    s   [{'no_1': '78', 'no_2': '103', 'no_3': '356'}]  Yoo
8   1123.1  Hz  [{'no_1': '21', 'no_2': '43', 'no_3': '3577'}]  Baz
9   43      m   [{'no_1': '45', 'no_2': '1038', 'no_3': '356'}] Foo
10  54.1    s   [{'no_1': '78', 'no_2': '103', 'no_3': '356'}]  Yoo
11  1123.1  Hz  [{'no_1': '21', 'no_2': '43', 'no_3': '3577'}]  Baz

< /code>
So it is exploding each JSON in 3 rows (admitteldy each JSON does contain 3 sub-dicts, so to say).

I actually would like Foo
, yoo und baz in derselben Zeile dokumentiert werden, wobei Spalten hinzugefügt werden. Ich würde gerne einen Ihrer ausgefallenen Einzeiler sehen, vielen Dank für Ihre Hilfe

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post