การจัดการกับคอลัมน์ข้อมูลแบบซ้อน

การจัดรูปแบบข้อมูลด้วย pandas

Maria Eugenia Inzaugarat

Data Scientist

ทบทวน

  • วิธีอ่าน JSON แบบซ้อนเข้าสู่ DataFrame โดยใช้ json_normalize()
การจัดรูปแบบข้อมูลด้วย 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...