본문 바로가기
study/python

파이썬 pandas - 데이터프레임(DataFrame) 생성 및 데이터 출력

by kuah_ 2022. 7. 28.

 

 

 

 

데이터프레임 (DataFrame)

- 시리즈의 결합. 시리즈 객체가 컬럼이 됨.

- 기본 인덱스는 0부터 시작되며, 사용자 인덱스를 지정하더라도 rangeindex(rownum)이 유지됨

- 같은 인덱스를 가진 시리즈끼리 결합할 경우 수월함

- 데이터 수집 > 시리즈 생성하여 데이터프레임 생성(현재과정) > 시각화

 

 

 

데이터프레임 생성
1
2
3
4
5
6
7
8
dates = pd.date_range('2021-07-01','2021-07-06'# 날짜
temps1 = pd.Series([80,82,85,90,83,87], index=dates) # 날짜를 인덱스로 temp1 시리즈 생성
temps2 = pd.Series([70,75,69,83,79,77], index=dates) # 날짜를 인덱스로 temp2 시리즈 생성
temps_diff = temps1-temps2 # 시리즈끼리 연산하여 새로운 시리즈를 생성
 
dic = {'France': temps1,'Netherland': temps2,'Difference':temps_diff}
temps_df = pd.DataFrame(dic)
temps_df # ipynb 파일로 실행시 마지막 출력문은 print 
cs

 

출력결과

 

 

 

Q1. [75, 77, 67, 82, 77, 85]의 값으로 이루어진 'Germany' 시리즈를 생성하고

    위에서 생성한 France, Netherland까지 세 시리즈로 데이터프레임을 생성한 후 각 도시의 평균 기온을 출력

 

A.

1
2
3
4
5
6
7
8
9
10
11
temps3 = pd.Series([757767827785], index=dates)
temps_df2 = pd.DataFrame(
        {
        'France': temps1,
        'Netherland': temps2,
        'Germany': temps3,
        }
)
print('France \t평균기온 : {0:.2f}'.format(temps1.mean())) # pandas에서 제공하는 mean 함수로 평균 계산
print(temps_df2.columns.values[1] ,'\t평균기온 : {}'.format(round(temps_df2.Netherland.mean(),2)))
print(temps_df2.columns.values[2] ,'\t평균기온 : {0:.2f}'.format(temps_df2.Germany.mean())   
cs

 

 

 

컬럼 추가, 컬럼명 변경, 특정 컬럼 출력

- 추가 : 데이터프레임명[컬럼명] = 리스트 또는 시리즈

- 변경 : .columns를 활용하여 조회 및 변경

- 특정 : 

1
2
3
temps_df['France']
temps_df.France # 1번 라인과 같이 인덱스와 France 컬럼 출력
temps_df[['France','Germany']] # 두 개 이상의 컬럼(시리즈)을 한번에 가져올 때에는 대괄호 중첩
cs

 

 

Q2. 행별 합을 구하여 Q1에서 생성한 데이터 프레임에 'Sum' 컬럼을 추가

 

A. 

1
2
3
temps_sum = temps1+temps2+temps3
temps_df['Sum'= temps_sum
temps_df
cs

 

 

 

Q3. 컬럼명을 'Sum'에서 'Total'로 변경

 

A

1
2
3
4
print(list(temps_df.columns)) # 컬럼명 목록 출력
col_list[3= 'Total' # 세번째 컬럼명을 Total로 변경
temps_df.columns = col_list # 컬럼명으로 반영
print(list(temps_df.columns))
cs

 

 

Q4. temps_df의 Netherlands 시리즈에서 맨 아래 3행을 추출 (* 아래 타입은 출력되지 않아도 됨)

 

A. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# ver.1
print(temps_df.Netherlands[-3:]) # 슬라이싱 활용하여 출력
print('-'*40)
 
# 슬라이싱 다양하게 활용
# ver.2
print(temps_df.Netherlands[3:6]) 
print('-'*40)
 
# ver.3
print(temps_df[['Netherlands']][3:]) 
print('-'*40)
 
# ver.4
print(temps_df.loc['20210704':'20210706',['Netherlands']])
cs

 

 

Q5. temps_df의 Germany 시리즈에서 기온이 80 이상인 행을 추출 (* 아래 타입은 출력되지 않아도 됨)

 

A. 

1
2
3
4
5
6
7
8
9
10
11
# 조건문을 넣을 수 있음
# ver.1
print(temps_df.Germany[temps_df.Germany >= 80])
print('-'*40)
 
# ver.2
print(temps_df[temps_df.Germany >= 80].Germany)
 
# 둘의 차이
# Germany 시리즈를 추출한 후 조건문을 실행하여 행을 추출하느냐
# 조건문을 실행하여 행을 추출한 후 Germany 시리즈를 추출하느냐
cs

 

 

 

 

댓글