중첩 데이터 열 다루기

pandas로 데이터 재구조화하기

Maria Eugenia Inzaugarat

Data Scientist

복습

  • json_normalize()로 중첩 JSON을 DataFrame으로 읽는 방법.
pandas로 데이터 재구조화하기

열에 있는 중첩 데이터

writers = ["Mary Shelley", "Ernest Hemingway"]
books = ["{'title': 'Frankenstein', 'year': 1818}", 
        "{'title': 'The Old Man and the Sea', 'year': 1951}"]

collection = pd.DataFrame( )
pandas로 데이터 재구조화하기

열에 있는 중첩 데이터

writers = ["Mary Shelley", "Ernest Hemingway"]
books = ["{'title': 'Frankenstein', 'year': 1818}", 
        "{'title': 'The Old Man and the Sea', 'year': 1951}"]

collection = pd.DataFrame(dict( ))
pandas로 데이터 재구조화하기

열에 있는 중첩 데이터

writers = ["Mary Shelley", "Ernest Hemingway"]
books = ['{"title": "Frankenstein", "year": "1818"}',
         '{"title": "The Old Man and the Sea", "year":"1951"}']

collection = pd.DataFrame(dict(writers=writers, books=books))
collection
            writers                                               books
0      Mary Shelley             {'title': 'Frankenstein', 'year': 1818}
1  Ernest Hemingway  {'title': 'The Old Man and the Sea', 'year': 1951}
pandas로 데이터 재구조화하기

중첩 데이터 변환

import json

books = collection['books']
pandas로 데이터 재구조화하기

중첩 데이터 변환

import json

books = collection['books'].apply( )
pandas로 데이터 재구조화하기

중첩 데이터 변환

import json

books = collection['books'].apply(json.loads)
pandas로 데이터 재구조화하기

중첩 데이터 변환

import json

books = collection['books'].apply(json.loads).apply(pd.Series)
books
                     title  year
0             Frankenstein  1818
1  The Old Man and the Sea  1951
pandas로 데이터 재구조화하기

다시 병합하기

collection = collection.drop(columns='books')

pd.concat([collection, books], axis=1)
            writers                    title  year
0      Mary Shelley             Frankenstein  1818
1  Ernest Hemingway  The Old Man and the Sea  1951
pandas로 데이터 재구조화하기

중첩 데이터 덤프하기

import json
books = collection['books'].apply(json.loads)



pandas로 데이터 재구조화하기

중첩 데이터 덤프하기

import json
books = collection['books'].apply(json.loads).to_list()

books_dump = json.dumps(books)
new_books = pd.read_json(books_dump)
new_books
                     title  year
0             Frankenstein  1818
1  The Old Man and the Sea  1951
pandas로 데이터 재구조화하기

중첩 데이터 덤프하기

pd.concat([collection['writers'], new_books], axis=1)
            writers                    title  year
0      Mary Shelley             Frankenstein  1818
1  Ernest Hemingway  The Old Man and the Sea  1951
pandas로 데이터 재구조화하기

연습해 봅시다!

pandas로 데이터 재구조화하기

Preparing Video For Download...