본문 바로가기

Trouble Shooting

[pandas/reindex 에러] ValueError: cannot reindex from a duplicate axis

728x90

 

이 에러를 마주한 사람들은 분명 다음의 코드와 같이 dataframe을 reindex하는 과정에서 문제가 발생했을 것이다.

new_df = df.set_index('previous_idx').reindex('new_idx')

 

해결방안

1) 다음의 코드를 넣어보고 결과를 출력해보자

unique는 중복한 값이 없는지 확인하는 함수이다

print(df['previous_idx'].is_unique)

혹시 위 출력의 결과가 False 인가?

 

2) 그렇다면 위 값에 중복된 값이 있기에 index로 설정하는 과정에서 문제가 발생하는 것이다. 

중복된 값을 없애주면 문제가 해결된다

 df = df.drop_duplicates(subset=['previous_idx'])

 

3) 중복된 값이 잘 사라졌는지 다시 확인

print(df['previous_idx'].is_unique)

True가 출력된다면 성공이다

 

다시 reindex를 해보면 오류가 나지 않을 것이다. 

new_df = df.set_index('previous_idx').reindex('new_idx')
반응형