1. 특정 조건에 맞는 결과 출력

조건

  1. 항목에 '대형'이 포함된 문자열
  2. 항목이 '재래시장'이거나 '쇼핑몰'
#특정 문자열이 포함 결과 출력(str.contains())
dfShop1 = df[df['항목'].str.contains('대형')]

#조건에 맞는 결과 출력(df.query())
dfShop2 = df.query("항목 == '재래시장' | 항목 == '쇼핑몰'")

#데이터프레임 병합(pd.concat())
dfShop = pd.concat([dfShop1, dfShop2])

#1. 시점 오름차순(ascending=True)
#2. 인덱스 무시(ignore_index=True ➡️ 기존 인덱스 무시하고 새롭게 0, 1, 2순)
dfShop = dfShop.sort_values('시점', ascending=True, ignore_index = True)

dfShop.head()
시점항목15~19세20대30대40대50대60대70세 이상
02016대형마트5.5624.227.82219.712.1
12016대형서점4.32.50.60.80.30.10
22016쇼핑몰9.715.214.114.59.24.52.1
32016재래시장0.41.34.17.214.22330
42018대형마트2.74.618.724.520.614.810.6

➕참고 사이트 | 값 기준 정렬 (sort_values)

2. 그룹별 합계

#1. 그룹별('시점') 합계
#2. #그룹화할 내용 인덱스 기존 유지(as_index=False)
dfEatYear = dfEat.groupby('시점', as_index=False).sum()

#인덱스 내용 변경('시점')
dfEatYear = dfEatYear.set_index("시점")

dfEatYear.head(3)
시점항목15~19세20대30대40대50대60대70세 이상
2016식당커피숍40.380.862.955.147.634.424.2
2018식당커피숍40.177.367.760.257.346.532.6
2019식당카페44.074.269.856.251.142.732.9

➕참고 사이트 | 그룹화 계산 (groupby)

※ 합계 계산 안될 경우

시점항목15~19세20대30대40대50대60대70세 이상
142020대형서점0.110.70.50.40.1-
dfShop = dfShop.replace('-', 0)
시점항목15~19세20대30대40대50대60대70세 이상
142020대형서점0.110.70.50.40.10

3. 파생변수

#새 열 할당(df.assign())
dfEatYear = dfEatYear.assign(
	#열 name = lambda 매개변수(dfEatYeear를 x로 대체): ~표현식~
    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.380.862.955.147.634.424.2345.353.28699729.74225316.970750
2018식당커피숍40.177.367.760.257.346.532.6381.748.49358130.78333820.723081
2019식당카페44.074.269.856.251.142.732.9370.950.68751728.92963120.382853

➕참고 사이트 | 새 열 할당 (assign)

4. 재구성 & 반올림

#데이터프레임 재구성
dfEatYear = dfEatYear.iloc[:,[9,10,11]]

#컬럼명 변경
dfEatYear.columns = ['15세~30대', '40대·50대', '60대 이상']

#소수점 반올림해서 일의자리까지(df.round(1))
dfEatFinal = dfEatYear.round(1)

dfEatFinal.head(3)
시점15세~30대40대·50대60대 이상
201653.329.717.0
201848.530.820.7
201950.728.920.4

※ 반올림 안 될 경우

반올림 안 되는 사례

  1. 데이터프레임의 데이터 타입 확인
코드결과
dfLeisureFianl.dtypes데이터 타입 확인
  1. 데이터 타입이 object일 경우 float64로 변경
코드결과
dfLeisureFianl.astype('float64')데이터 타입 변경
profile
은서는 오늘도 개발 중💻

0개의 댓글

Powered by GraphCDN, the GraphQL CDN