개발/Python

Pandas reset_index() error

강서버 2024. 2. 20. 16:59
728x90
반응형

[ CSV file read ]

>>> import pandas as pd

 

>>> df1 = pd.read_csv('sample.csv')

>>> df1

  StdID  Middle  Final
0   S01      90     95
1   S02      82     83
2   S03      80     78
3   S04      78     75
4   S05      93     91

 

[ 'StdID' set index ]

>>> df1.set_index('StdID', inplace=True)

>>> df1

       Middle  Final
StdID
S01        90     95
S02        82     83
S03        80     78
S04        78     75
S05        93     91

 

* inplace=True option

df1.set_index('StdID', inplace=True)

=> df1 = df1.set_index('StdID')

 

[ reset index ]

>>> df1.reset_index(inplace=True)

>>> df1

  StdID  Middle  Final
0   S01      90     95
1   S02      82     83
2   S03      80     78
3   S04      78     75
4   S05      93     91

 

[ 'StdID' index set ]

>>> df1.index = df1['StdID']

>>> df1

      StdID  Middle  Final
StdID
S01     S01      90     95
S02     S02      82     83
S03     S03      80     78
S04     S04      78     75
S05     S05      93     91

 

[ reset index ]

>>> df1.reset_index(inplace=True)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\devel\Python\Python39\lib\site-packages\pandas\util\_decorators.py", line 311, in wrapper
    return func(*args, **kwargs)
  File "C:\devel\Python\Python39\lib\site-packages\pandas\core\frame.py", line 5839, in reset_index
    new_obj.insert(0, name, level_values)
  File "C:\devel\Python\Python39\lib\site-packages\pandas\core\frame.py", line 4440, in insert
    raise ValueError(f"cannot insert {column}, already exists")
ValueError: cannot insert StdID, already exists

 

=> resolve

>>> df1.reset_index(drop=True, inplace=True)

>>> df1

  StdID  Middle  Final
0   S01      90     95
1   S02      82     83
2   S03      80     78
3   S04      78     75
4   S05      93     91

 

728x90
반응형