-
pandas dataframe index, column 가져오고 변경하기python 기초 2024. 8. 27. 21:40728x90
pandas dataframe의 index와 column을 가져오고, 변경하는 방법은 아래와 같다
import numpy as np import pandas as pd import sklearn
In [3]:A=np.random.sample(10)*5+2 B=np.random.sample(10)*2+3 C=np.random.sample(10)*3-1 df=pd.DataFrame({'A':A, 'B':B, 'C':C}) df
Out[3]:A B C 0 6.161620 4.609621 -0.186786 1 3.937665 4.936775 0.969055 2 3.882688 4.034569 1.483390 3 5.857642 3.107870 1.665433 4 4.728388 3.322217 -0.494691 5 4.871471 4.859152 0.801952 6 5.742581 4.162347 0.005457 7 5.022636 4.203201 -0.690801 8 6.348671 4.736056 -0.929213 9 2.979743 3.602551 1.888747 In [4]:df.index # index 정보 가져오기
Out[4]:RangeIndex(start=0, stop=10, step=1)
In [5]:df.columns # column 정보 가져오기
Out[5]:Index(['A', 'B', 'C'], dtype='object')
In [6]:df.set_index(np.array(range(9,-1,-1))) # index를 변경
Out[6]:A B C 9 6.161620 4.609621 -0.186786 8 3.937665 4.936775 0.969055 7 3.882688 4.034569 1.483390 6 5.857642 3.107870 1.665433 5 4.728388 3.322217 -0.494691 4 4.871471 4.859152 0.801952 3 5.742581 4.162347 0.005457 2 5.022636 4.203201 -0.690801 1 6.348671 4.736056 -0.929213 0 2.979743 3.602551 1.888747 In [7]:df.rename(columns={'A':'Apple','B':'Banana'}) # column 이름 변경
Out[7]:Apple Banana C 0 6.161620 4.609621 -0.186786 1 3.937665 4.936775 0.969055 2 3.882688 4.034569 1.483390 3 5.857642 3.107870 1.665433 4 4.728388 3.322217 -0.494691 5 4.871471 4.859152 0.801952 6 5.742581 4.162347 0.005457 7 5.022636 4.203201 -0.690801 8 6.348671 4.736056 -0.929213 9 2.979743 3.602551 1.888747 728x90'python 기초' 카테고리의 다른 글
Python의 datetime 모듈 활용법 (0) 2025.02.17 pd crosstab 사용 (0) 2024.10.20 sklearn standard scaler (0) 2024.08.27 pandas read_csv sep 옵션 (0) 2024.08.25 pandas dadtaframe 수치형 / 범주형 분리 (0) 2024.08.24