개발/파이썬

`ValueError: cannot reindex from a duplicate axis` 오류 수정하기

맨날치킨 2023. 2. 9. 10:05
반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

What does `ValueError: cannot reindex from a duplicate axis` mean?

`ValueError: cannot reindex from a duplicate axis`는 무엇인가요?

 문제 내용 

I am getting a ValueError: cannot reindex from a duplicate axis when I am trying to set an index to a certain value. I tried to reproduce this with a simple example, but I could not do it.

특정 값을 인덱스로 설정할 때 ValueError: cannot reindex from a duplicate axis 오류가 발생합니다. 이 오류를 재현하기 위해 간단한 예제를 만들어 봤지만, 실패했습니다.

 

Here is my session inside of ipdb trace. I have a DataFrame with string index, and integer columns, float values. However when I try to create sum index for sum of all columns I am getting ValueError: cannot reindex from a duplicate axis error. I created a small DataFrame with the same characteristics, but was not able to reproduce the problem, what could I be missing?

여기는 ipdb 트레이스 내부의 세션입니다. 저는 문자열 인덱스와 정수 열, 부동 소수점 값으로 구성된 DataFrame이 있습니다. 그러나 모든 열의 합 인덱스를 만들려고하면 ValueError: cannot reindex from a duplicate axis 오류가 발생합니다. 동일한 특성을 가진 작은 DataFrame을 만들었지만 문제를 재현하지 못했습니다. 무엇을 놓치고 있는 걸까요?

 

I don't really understand what ValueError: cannot reindex from a duplicate axismeans, what does this error message mean? Maybe this will help me diagnose the problem, and this is most answerable part of my question.

ValueError: can reindex from a duplicate axis가 무엇을 의미하는지 잘 모르겠습니다. 이 오류 메시지는 무엇을 의미합니까? 아마도 이것은 내가 문제를 진단하는 데 도움이 될 것이며 이것이 내 질문에서 가장 대답할 수 있는 부분입니다.
ipdb> type(affinity_matrix)
<class 'pandas.core.frame.DataFrame'>
ipdb> affinity_matrix.shape
(333, 10)
ipdb> affinity_matrix.columns
Int64Index([9315684, 9315597, 9316591, 9320520, 9321163, 9320615, 9321187, 9319487, 9319467, 9320484], dtype='int64')
ipdb> affinity_matrix.index
Index([u'001', u'002', u'003', u'004', u'005', u'008', u'009', u'010', u'011', u'014', u'015', u'016', u'018', u'020', u'021', u'022', u'024', u'025', u'026', u'027', u'028', u'029', u'030', u'032', u'033', u'034', u'035', u'036', u'039', u'040', u'041', u'042', u'043', u'044', u'045', u'047', u'047', u'048', u'050', u'053', u'054', u'055', u'056', u'057', u'058', u'059', u'060', u'061', u'062', u'063', u'065', u'067', u'068', u'069', u'070', u'071', u'072', u'073', u'074', u'075', u'076', u'077', u'078', u'080', u'082', u'083', u'084', u'085', u'086', u'089', u'090', u'091', u'092', u'093', u'094', u'095', u'096', u'097', u'098', u'100', u'101', u'103', u'104', u'105', u'106', u'107', u'108', u'109', u'110', u'111', u'112', u'113', u'114', u'115', u'116', u'117', u'118', u'119', u'121', u'122', ...], dtype='object')

ipdb> affinity_matrix.values.dtype
dtype('float64')
ipdb> 'sums' in affinity_matrix.index
False

 

Here is the error:

다음은 에러 메시지입니다.
ipdb> affinity_matrix.loc['sums'] = affinity_matrix.sum(axis=0)
*** ValueError: cannot reindex from a duplicate axis

 

I tried to reproduce this with a simple example, but I failed

간단한 예제를 만들어서 재현해 보려고 했지만 실패했습니다.
In [32]: import pandas as pd

In [33]: import numpy as np

In [34]: a = np.arange(35).reshape(5,7)

In [35]: df = pd.DataFrame(a, ['x', 'y', 'u', 'z', 'w'], range(10, 17))

In [36]: df.values.dtype
Out[36]: dtype('int64')

In [37]: df.loc['sums'] = df.sum(axis=0)

In [38]: df
Out[38]: 
      10  11  12  13  14  15   16
x      0   1   2   3   4   5    6
y      7   8   9  10  11  12   13
u     14  15  16  17  18  19   20
z     21  22  23  24  25  26   27
w     28  29  30  31  32  33   34
sums  70  75  80  85  90  95  100

 

 

 높은 점수를 받은 Solution 

This error usually rises when you join / assign to a column when the index has duplicate values. Since you are assigning to a row, I suspect that there is a duplicate value in affinity_matrix.columns, perhaps not shown in your question.

이 오류는 일반적으로 인덱스에 중복 값이 있을 때 열을 결합/할당할 때 발생합니다. 당신이 행에 할당하고 있다는 것을 감안할 때, 내가 의심하는 것은 affinity_matrix.columns에 중복 값이 있을 것이라는 것입니다. 아마도 당신이 질문에서는 보이지 않은 것일 수도 있습니다.

 

 

 

 가장 최근 달린 Solution 

Simple Fix

간단한 해결책

 

Run this before grouping

그룹화 전에 이것을 실행하세요.
df = df.reset_index()

 

Thanks to this github comment for the solution.

해당 문제의 해결 방법은 GitHub에서 올라온 댓글로부터 얻었습니다.

 

 

 

출처 : https://stackoverflow.com/questions/27236275/what-does-valueerror-cannot-reindex-from-a-duplicate-axis-mean

반응형