[ 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
'개발 > Python' 카테고리의 다른 글
Pandas DataFrame mean(), median(), std(), var(), corr() FutureWarning (0) | 2024.03.26 |
---|---|
Pandas DataFrame FutureWarning (0) | 2024.03.13 |
구글 코랩 판다스 read_csv 인코딩 오류 (0) | 2024.02.17 |
로또 번호 생성기, 로또 6/45 (0) | 2023.12.15 |
Windows pandas read_csv UnicodeDecodeError (0) | 2023.11.18 |