Python/Pandas Tutorial

[Python Pandas] pandas table sorting by other table's column

슈퍼짱짱 2021. 3. 19. 10:49
반응형

2개의 Pandas DataFrame A, B가 있을 때, B 테이블의 하나의 컬럼을 기준으로 A 테이블을 sorting 하는 방법을 알아보겠다.

 

예로 다음 두 DataFrame이 있다고 하자.

import padnas as pd

## create A table
A = pd.DataFrame({'col1' : ['d','b','a','e','c'],
                 'col2' : [1,6,9,3,6]})
                 
## create B table
B = pd.DataFrame({'standard_col' : ['a','b','c','d','e'],
                 'col3' : [1,2,3,4,5]})

 

A table의 'col1' 컬럼과 B table의 'standard_col' 의 요소가 동일하다. 이 때, A table을 B table의 'standard_col' 컬럼에 맞추어 다음과 같이 sorting 하는 것이 목적이다.

 


방법은 A 테이블의 index를 'col1' 로 지정해주고, B 테이블에서 'standard_col' 를 기준으로 reindex 해주면 된다.

 

A = A.set_index('col1')
A = A.reindex(index=B['standard_col'])

 

마지막으로 reset_index() 해주면 index가 column으로 생성된다.

 

단, 기존에 A table의 'col1' 이 B table의 'standar_col'로 이름이 바뀌기 때문에 원치 않는 경우, rename() 으로 이름을 변경해주면 된다.

 

 

반응형