1. 특정 조건에 맞는 결과 출력
조건
- 항목에 '대형'이 포함된 문자열
- 항목이 '재래시장'이거나 '쇼핑몰'
dfShop1 = df[df['항목'].str.contains('대형')]
dfShop2 = df.query("항목 == '재래시장' | 항목 == '쇼핑몰'")
dfShop = pd.concat([dfShop1, dfShop2])
dfShop = dfShop.sort_values('시점', ascending=True, ignore_index = True)
dfShop.head()
| 시점 | 항목 | 15~19세 | 20대 | 30대 | 40대 | 50대 | 60대 | 70세 이상 |
---|
0 | 2016 | 대형마트 | 5.5 | 6 | 24.2 | 27.8 | 22 | 19.7 | 12.1 |
1 | 2016 | 대형서점 | 4.3 | 2.5 | 0.6 | 0.8 | 0.3 | 0.1 | 0 |
2 | 2016 | 쇼핑몰 | 9.7 | 15.2 | 14.1 | 14.5 | 9.2 | 4.5 | 2.1 |
3 | 2016 | 재래시장 | 0.4 | 1.3 | 4.1 | 7.2 | 14.2 | 23 | 30 |
4 | 2018 | 대형마트 | 2.7 | 4.6 | 18.7 | 24.5 | 20.6 | 14.8 | 10.6 |
➕참고 사이트 | 값 기준 정렬 (sort_values)
2. 그룹별 합계
dfEatYear = dfEat.groupby('시점', as_index=False).sum()
dfEatYear = dfEatYear.set_index("시점")
dfEatYear.head(3)
시점 | 항목 | 15~19세 | 20대 | 30대 | 40대 | 50대 | 60대 | 70세 이상 |
---|
2016 | 식당커피숍 | 40.3 | 80.8 | 62.9 | 55.1 | 47.6 | 34.4 | 24.2 |
2018 | 식당커피숍 | 40.1 | 77.3 | 67.7 | 60.2 | 57.3 | 46.5 | 32.6 |
2019 | 식당카페 | 44.0 | 74.2 | 69.8 | 56.2 | 51.1 | 42.7 | 32.9 |
➕참고 사이트 | 그룹화 계산 (groupby)
※ 합계 계산 안될 경우
| 시점 | 항목 | 15~19세 | 20대 | 30대 | 40대 | 50대 | 60대 | 70세 이상 |
---|
14 | 2020 | 대형서점 | 0.1 | 1 | 0.7 | 0.5 | 0.4 | 0.1 | - |
dfShop = dfShop.replace('-', 0)
| 시점 | 항목 | 15~19세 | 20대 | 30대 | 40대 | 50대 | 60대 | 70세 이상 |
---|
14 | 2020 | 대형서점 | 0.1 | 1 | 0.7 | 0.5 | 0.4 | 0.1 | 0 |
3. 파생변수
dfEatYear = dfEatYear.assign(
total = lambda x: x['15~19세'] + x['20대'] + x['30대'] + x['40대'] + x['50대'] + x['60대'] + x['70세 이상'],
일번 = lambda x: ((x['15~19세'] + x['20대'] + x['30대']) / x['total'])*100,
이번 = lambda x: ((x['40대'] + x['50대']) / x['total'])*100,
삼번 = lambda x: ((x['60대'] + x['70세 이상']) / x['total'])*100
)
dfEatYear.head(3)
시점 | 항목 | 15~19세 | 20대 | 30대 | 40대 | 50대 | 60대 | 70세 이상 | total | 일번 | 이번 | 삼번 |
---|
2016 | 식당커피숍 | 40.3 | 80.8 | 62.9 | 55.1 | 47.6 | 34.4 | 24.2 | 345.3 | 53.286997 | 29.742253 | 16.970750 |
2018 | 식당커피숍 | 40.1 | 77.3 | 67.7 | 60.2 | 57.3 | 46.5 | 32.6 | 381.7 | 48.493581 | 30.783338 | 20.723081 |
2019 | 식당카페 | 44.0 | 74.2 | 69.8 | 56.2 | 51.1 | 42.7 | 32.9 | 370.9 | 50.687517 | 28.929631 | 20.382853 |
➕참고 사이트 | 새 열 할당 (assign)
4. 재구성 & 반올림
dfEatYear = dfEatYear.iloc[:,[9,10,11]]
dfEatYear.columns = ['15세~30대', '40대·50대', '60대 이상']
dfEatFinal = dfEatYear.round(1)
dfEatFinal.head(3)
시점 | 15세~30대 | 40대·50대 | 60대 이상 |
---|
2016 | 53.3 | 29.7 | 17.0 |
2018 | 48.5 | 30.8 | 20.7 |
2019 | 50.7 | 28.9 | 20.4 |
※ 반올림 안 될 경우

- 데이터프레임의 데이터 타입 확인
코드 | 결과 |
---|
dfLeisureFianl.dtypes |  |
- 데이터 타입이 object일 경우 float64로 변경
코드 | 결과 |
---|
dfLeisureFianl.astype('float64') |  |