무결성 검증

pandas로 데이터 조인하기

Aaren Stubberfield

Instructor

데이터를 확인해 봅시다

가능한 병합 문제:

두 개의 데이터세트를 수평으로 나란히 배치한 일대다 관계

  • 의도하지 않은 일대다 관계
  • 의도하지 않은 다대다 관계

가능한 결합 문제:

두 번째 DataFrame에 중복 행이 있는, 수직으로 결합된 두 개의 DataFrame

  • 중복 레코드가 의도치 않게 추가되었을 수 있음
pandas로 데이터 조인하기

병합 검증

.merge(validate=None):

  • 병합이 지정된 유형인지 확인합니다
  • 'one_to_one'
  • 'one_to_many'
  • 'many_to_one'
  • 'many_to_many'
pandas로 데이터 조인하기

데이터세트 병합 예시

테이블 이름: 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   

테이블 이름: specs

  tid  milliseconds  bytes  
0 2    342562        5510424
1 3    230619        3990994
2 2    252051        4331779
pandas로 데이터 조인하기

병합 검증: 일대일

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
pandas로 데이터 조인하기

병합 검증: 일대다

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   
pandas로 데이터 조인하기

결합 검증

.concat(verify_integrity=False):

  • 새로 연결된 인덱스에 중복이 있는지 확인
  • 기본값은 False
pandas로 데이터 조인하기

.concat() 예시용 데이터세트

테이블 이름: 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 

테이블 이름: 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 
pandas로 데이터 조인하기

결합 검증: 예시

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
pandas로 데이터 조인하기

무결성을 검증해야 하는 이유와 조치 방법

이유:

  • 현실의 데이터는 종종 깨끗하지 않음

해야 할 일:

  • 잘못된 데이터 수정
  • 중복 행 삭제
pandas로 데이터 조인하기

연습해 봅시다!

pandas로 데이터 조인하기

Preparing Video For Download...