Xác minh tính toàn vẹn

Kết hợp dữ liệu với pandas

Aaren Stubberfield

Instructor

Kiểm tra dữ liệu của bạn

Vấn đề khi merge có thể gặp:

Hai DataFrame ghép ngang với quan hệ một-nhiều

  • Quan hệ một-nhiều ngoài ý muốn
  • Quan hệ nhiều-nhiều ngoài ý muốn

Vấn đề khi nối có thể gặp:

Hai DataFrame ghép dọc với hàng trùng trong DataFrame thứ hai

  • Có thể vô tình thêm bản ghi trùng lặp
Kết hợp dữ liệu với pandas

Xác thực merge

.merge(validate=None):

  • Kiểm tra kiểu merge được chỉ định
  • 'one_to_one'
  • 'one_to_many'
  • 'many_to_one'
  • 'many_to_many'
Kết hợp dữ liệu với pandas

Tập dữ liệu cho ví dụ merge

Tên bảng: tracks

  tid  name             aid  mtid  gid  u_price
0 2    Balls to the...  2    2     1    0.99   
1 3    Fast As a Shark  3    2     1    0.99   
2 4    Restless and...  3    2     1    0.99   

Tên bảng: specs

  tid  milliseconds  bytes  
0 2    342562        5510424
1 3    230619        3990994
2 2    252051        4331779
Kết hợp dữ liệu với pandas

Xác thực merge: one_to_one

tracks.merge(specs, on='tid', 
             validate='one_to_one')
Traceback (most recent call last):
MergeError: Merge keys are not unique in right dataset; not a one-to-one merge
Kết hợp dữ liệu với pandas

Xác thực merge: one_to_many

albums.merge(tracks, on='aid', 
             validate='one_to_many')
  aid  title            artid  tid  name             mtid  gid  u_price
0 2    Balls to the...  2      2    Balls to the...  2     1    0.99   
1 3    Restless and...  2      3    Fast As a Shark  2     1    0.99   
2 3    Restless and...  2      4    Restless and...  2     1    0.99   
Kết hợp dữ liệu với pandas

Xác minh khi nối (concat)

.concat(verify_integrity=False):

  • Kiểm tra chỉ mục mới sau nối có trùng lặp không
  • Mặc định là False
Kết hợp dữ liệu với pandas

Tập dữ liệu cho ví dụ .concat()

Tên bảng: inv_feb

     cid  invoice_date  total
iid 
7    38   2009-02-01    1.98 
8    40   2009-02-01    1.98 
9    42   2009-02-02    3.96 

Tên bảng: inv_mar

     cid  invoice_date  total
iid 
9    17   2009-03-04    1.98 
15   19   2009-03-04    1.98 
16   21   2009-03-05    3.96 
Kết hợp dữ liệu với pandas

Xác minh nối (concat): ví dụ

pd.concat([inv_feb, inv_mar], 
          verify_integrity=True)
Traceback (most recent call last):
ValueError: Indexes have overlapping 
values: Int64Index([9], dtype='int64', 
name='iid')
pd.concat([inv_feb, inv_mar], 
          verify_integrity=False)
     cid  invoice_date  total
iid 
7    38   2009-02-01    1.98 
8    40   2009-02-01    1.98 
9    42   2009-02-02    3.96 
9    17   2009-03-04    1.98 
15   19   2009-03-04    1.98 
16   21   2009-03-05    3.96
Kết hợp dữ liệu với pandas

Vì sao cần xác minh và cách xử lý

Vì sao:

  • Dữ liệu thực tế thường KHÔNG sạch

Cách xử lý:

  • Sửa dữ liệu sai
  • Xóa hàng trùng
Kết hợp dữ liệu với pandas

Ayo berlatih!

Kết hợp dữ liệu với pandas

Preparing Video For Download...