logo

[python-ds] 판다스: 인덱스

import pandas as pd
df = pd.read_excel('census.xlsx')
df.head()
ageworkclassfnlwgteducationeducation_nummarital_statusoccupationrelationshipracesexcapital_gaincapital_losshours_per_weeknative_countryincome
039State-gov77516Bachelors13Never-marriedAdm-clericalNot-in-familyWhiteMale2174040United-States<=50K
150Self-emp-not-inc83311Bachelors13Married-civ-spouseExec-managerialHusbandWhiteMale0013United-States<=50K
238Private215646HS-grad9DivorcedHandlers-cleanersNot-in-familyWhiteMale0040United-States<=50K
353Private23472111th7Married-civ-spouseHandlers-cleanersHusbandBlackMale0040United-States<=50K
428Private338409Bachelors13Married-civ-spouseProf-specialtyWifeBlackFemale0040Cuba<=50K
 

인덱스

df.index
RangeIndex(start=0, stop=32561, step=1)
 

.loc과 .iloc

.loc: 판다스 인덱스 기준 .iloc: 순서 기준으로

df.loc[0]  # 인덱스 0번
age                          39
workclass             State-gov
fnlwgt                    77516
education             Bachelors
education_num                13
marital_status    Never-married
occupation         Adm-clerical
relationship      Not-in-family
race                      White
sex                        Male
capital_gain               2174
capital_loss                  0
hours_per_week               40
native_country    United-States
income                    <=50K
Name: 0, dtype: object
df.iloc[0]  # 0번째
age                          39
workclass             State-gov
fnlwgt                    77516
education             Bachelors
education_num                13
marital_status    Never-married
occupation         Adm-clerical
relationship      Not-in-family
race                      White
sex                        Male
capital_gain               2174
capital_loss                  0
hours_per_week               40
native_country    United-States
income                    <=50K
Name: 0, dtype: object

정렬을 하면 12318번 행이 제일 처음(0번째)에 나옴

df.sort_values('age').head()
ageworkclassfnlwgteducationeducation_nummarital_statusoccupationrelationshipracesexcapital_gaincapital_losshours_per_weeknative_countryincome
1231817Private12736611th7Never-marriedSalesOwn-childWhiteFemale008United-States<=50K
631217Private13275511th7Never-marriedSalesOwn-childWhiteMale0015United-States<=50K
3092717Private10847011th7Never-marriedOther-serviceOwn-childBlackMale0017United-States<=50K
1278717Local-gov30890111th7Never-marriedAdm-clericalOwn-childWhiteFemale0015United-States<=50K
2575517?4740711th7Never-married?Own-childWhiteMale0010United-States<=50K
df.sort_values('age').loc[0]  # 0번행
age                          39
workclass             State-gov
fnlwgt                    77516
education             Bachelors
education_num                13
marital_status    Never-married
occupation         Adm-clerical
relationship      Not-in-family
race                      White
sex                        Male
capital_gain               2174
capital_loss                  0
hours_per_week               40
native_country    United-States
income                    <=50K
Name: 0, dtype: object
df.sort_values('age').iloc[0]  # 나이순으로 정렬했을 때 0번째 나오는 12318번행
age                          17
workclass               Private
fnlwgt                   127366
education                  11th
education_num                 7
marital_status    Never-married
occupation                Sales
relationship          Own-child
race                      White
sex                      Female
capital_gain                  0
capital_loss                  0
hours_per_week                8
native_country    United-States
income                    <=50K
Name: 12318, dtype: object
 

행과 열 모두 가리키기

df.loc[0, 'age']  # 0번 행, age 열
39
df.iloc[0, 0]  # 0번째 행, 0번째 열
39
 

문자열로 된 인덱스

import numpy as np
am = df.groupby('race').agg({'age': np.mean, 'education_num': np.mean})
am
ageeducation_num
race
Amer-Indian-Eskimo37.1736339.311897
Asian-Pac-Islander37.74687210.960539
Black37.7679269.486236
Other33.4575658.841328
White38.76988110.135246
am.loc['Black', 'age']
37.7679257362356
am.iloc[2, 0]
37.7679257362356
 

슬라이싱

.loc은 Python의 일반적인 인덱싱과 달리 5:7이라고 하면 5, 6, 7을 모두 포함한다.

df.loc[5:7]
ageworkclassfnlwgteducationeducation_nummarital_statusoccupationrelationshipracesexcapital_gaincapital_losshours_per_weeknative_countryincome
537Private284582Masters14Married-civ-spouseExec-managerialWifeWhiteFemale0040United-States<=50K
649Private1601879th5Married-spouse-absentOther-serviceNot-in-familyBlackFemale0016Jamaica<=50K
752Self-emp-not-inc209642HS-grad9Married-civ-spouseExec-managerialHusbandWhiteMale0045United-States>50K
df.loc[5:7, 'age':'education']
ageworkclassfnlwgteducation
537Private284582Masters
649Private1601879th
752Self-emp-not-inc209642HS-grad

.iloc은 Python의 일반적인 인덱싱과 마찬가지로 5:7이라고 하면 6까지만 포함하고 7은 포함하지 않는다.

df.iloc[5:7]
ageworkclassfnlwgteducationeducation_nummarital_statusoccupationrelationshipracesexcapital_gaincapital_losshours_per_weeknative_countryincome
537Private284582Masters14Married-civ-spouseExec-managerialWifeWhiteFemale0040United-States<=50K
649Private1601879th5Married-spouse-absentOther-serviceNot-in-familyBlackFemale0016Jamaica<=50K
df.iloc[5:7,0:4]
ageworkclassfnlwgteducation
537Private284582Masters
649Private1601879th
 

실습

  1. education_num 순으로 정렬을 해보세요

  2. 위의 정렬한 데이터에서 첫 100명(0~99)을 뽑아보세요

  3. 위에서 뽑은 사람들의 age의 평균을 구해보세요.

df.sort_values('education_num').iloc[0:100].agg({'age': np.mean})
age    43.46
dtype: float64
 

무작위 고르기

df['age'].mean()
38.58164675532078
df.sample(1000)['age'].mean()
38.384
 

인덱스 바꾸기

d1 = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
d1
ab
014
125
236

특정 컬럼을 set_index를 이용해 인덱스로 바꿀 수 있다.

d2 = d1.set_index('b')
d2
a
b
41
52
63
d2.loc[4]
a    1
Name: 4, dtype: int64

reset_index를 하면 자동으로 0, 1, 2, ...으로 인덱스가 붙는다.

d2.reset_index()
ba
041
152
263

수동 지정

d3 = d1.copy()
d3.index = ['x', 'y', 'z']
d3
ab
114
025
236
 

멀티 인덱스

d4 = d1.copy()
d4.index = pd.MultiIndex.from_tuples([('x', 1), ('x', 2), ('y', 1)])
d4
ab
x114
225
y136

groupby를 할 때 결과가 멀티 인덱스 형태가 되는 경우가 많음

result = df.groupby(['race', 'sex']).agg({'age': [np.mean, np.median]})
result
age
meanmedian
racesex
Amer-Indian-EskimoFemale37.11764736
Male37.20833335
Asian-Pac-IslanderFemale35.08959533
............
OtherMale34.65432132
WhiteFemale36.81161835
Male39.65249838

10 rows × 2 columns

멀티 인덱스는 (a, b, c, ..) 순으로 표시

result.loc[('White', 'Female')]
age  mean      36.811618
     median    35.000000
Name: (White, Female), dtype: float64
result[('age', 'median')]
race                sex
Amer-Indian-Eskimo  Female    36
                    Male      35
Asian-Pac-Islander  Female    33
                              ..
Other               Male      32
White               Female    35
                    Male      38
Name: (age, median), Length: 10, dtype: int64
Previous
시본으로 집단 비교 시각화