Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- stable diffusion
- dp
- Generative Models
- 포스코 코딩테스트
- colorization
- 포스코 채용
- DDPM
- 프로그래머스
- 논문 리뷰
- kt인적성
- diffusion models
- ip-adapter
- Image Generation
- manganinja
- ddim
- classifier-free guidance
- KT
- 코딩테스트
- posco 채용
- controlNet
- 과제형 코딩테스트
Archives
- Today
- Total
Paul's Grit
[Python] [Data Analysis] Pandas 기초 본문
Pandas¶
- pandas는 데이터 분석과 조작(전처리)를 위한 오픈소스 라이브러리
- Series와 DataFrame이라는 데이터 타입을 이용
- 데이터 필터링, 정렬, 그룹화, 결측치처리, 시각화 등
- Pandas 데이터 타입
- Series
- index, values로 이루어진 데이터 타입
- DataFrame
- index, values, columns으로 이루어진 데이터 타입
- Series 데이터가 모이면 DataFrame
- Tabular, table 데이터라고 부르기도 함
- Series
In [3]:
# !pip install pandas
import numpy as np
import pandas as pd
01. Series¶
- index, values
In [7]:
# 선언
series = pd.Series([1, 2, 3, 4])
type(series)
Out[7]:
pandas.core.series.Series
In [13]:
# 오프셋 인덱스 적용가능
print(series[0])
print(series[1])
print(series[1:3])
print(type(series[2]))
1 2 1 2 2 3 dtype: int64 <class 'numpy.int64'>
In [14]:
# 시리즈 내부 데이터 타입
pd.Series([1, 2, 3], dtype=np.float64)
Out[14]:
0 1.0 1 2.0 2 3.0 dtype: float64
In [15]:
# 한 가지 데이터 타입만 인식
# object: 문자열 데이터를 의미
li = [1, 2, 3, '4']
pd.Series(li)
Out[15]:
0 1 1 2 2 3 3 4 dtype: object
In [19]:
series.index, series.values
Out[19]:
(RangeIndex(start=0, stop=4, step=1), array([1, 2, 3, 4]))
In [25]:
# 형변환
series = series.astype(np.float64)
print(series)
0 1.0 1 2.0 2 3.0 3 4.0 dtype: float64
In [41]:
# index 설정
data = pd.Series(np.random.randint(10, size = 5), list('ABCDE'))
print(data)
A 0 B 6 C 9 D 5 E 8 dtype: int64
In [42]:
data['A']
Out[42]:
0
In [43]:
# 문자열 index에 한해서 다음과 같이 접근 가능
data.A
Out[43]:
0
In [44]:
# 리스트 형태로 여러개 index에 접근 가능
data[['A', 'B']]
Out[44]:
A 0 B 6 dtype: int64
In [45]:
data[data > 5]
Out[45]:
B 6 C 9 E 8 dtype: int64
In [48]:
# 특정값, 예를 들어 누락값, 을 다른 값을 대체하는 경우
data[data > 5] = 999
print(data)
A 0 B 999 C 999 D 5 E 999 dtype: int64
In [49]:
# 브로드 캐스팅 연산
data * 10
Out[49]:
A 0 B 9990 C 9990 D 50 E 9990 dtype: int64
02. DataFrame¶
- Series()
- index, values
- DataFrame
- index, values, columns
In [124]:
dates = pd.date_range('20230804', periods=6)
df = pd.DataFrame(
data = np.random.randn(6, 4),
index = dates,
columns = ['A', 'B', 'C', 'D']
)
df
Out[124]:
A | B | C | D | |
---|---|---|---|---|
2023-08-04 | -0.225068 | 0.744492 | -1.402024 | -1.286209 |
2023-08-05 | 0.386276 | 0.283264 | 0.845932 | -0.284644 |
2023-08-06 | -0.763337 | 0.746245 | 0.620546 | 0.554813 |
2023-08-07 | 0.128081 | 0.743051 | -0.180613 | 0.525452 |
2023-08-08 | 1.543299 | 1.010273 | -0.222302 | -1.615143 |
2023-08-09 | -0.595848 | -1.593361 | -1.069847 | 0.377314 |
In [125]:
# 데이터 프래임 상단 정보 확인 (default: 5개)
df.head(2)
Out[125]:
A | B | C | D | |
---|---|---|---|---|
2023-08-04 | -0.225068 | 0.744492 | -1.402024 | -1.286209 |
2023-08-05 | 0.386276 | 0.283264 | 0.845932 | -0.284644 |
In [126]:
df.tail(3)
Out[126]:
A | B | C | D | |
---|---|---|---|---|
2023-08-07 | 0.128081 | 0.743051 | -0.180613 | 0.525452 |
2023-08-08 | 1.543299 | 1.010273 | -0.222302 | -1.615143 |
2023-08-09 | -0.595848 | -1.593361 | -1.069847 | 0.377314 |
In [127]:
df.info()
<class 'pandas.core.frame.DataFrame'> DatetimeIndex: 6 entries, 2023-08-04 to 2023-08-09 Freq: D Data columns (total 4 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 A 6 non-null float64 1 B 6 non-null float64 2 C 6 non-null float64 3 D 6 non-null float64 dtypes: float64(4) memory usage: 240.0 bytes
In [128]:
# 데이터 프래임 기술 통계 정보 요약
df.describe()
Out[128]:
A | B | C | D | |
---|---|---|---|---|
count | 6.000000 | 6.000000 | 6.000000 | 6.000000 |
mean | 0.078900 | 0.322327 | -0.234718 | -0.288070 |
std | 0.836470 | 0.967429 | 0.890214 | 0.956287 |
min | -0.763337 | -1.593361 | -1.402024 | -1.615143 |
25% | -0.503153 | 0.398210 | -0.857961 | -1.035818 |
50% | -0.048493 | 0.743771 | -0.201457 | 0.046335 |
75% | 0.321727 | 0.745807 | 0.420256 | 0.488417 |
max | 1.543299 | 1.010273 | 0.845932 | 0.554813 |
In [129]:
# 데이터 프래임 구성 3 요소
print(df.index)
print(df.columns)
print(df.values)
DatetimeIndex(['2023-08-04', '2023-08-05', '2023-08-06', '2023-08-07', '2023-08-08', '2023-08-09'], dtype='datetime64[ns]', freq='D') Index(['A', 'B', 'C', 'D'], dtype='object') [[-0.22506765 0.74449227 -1.40202444 -1.28620881] [ 0.38627585 0.2832635 0.84593208 -0.28464364] [-0.76333702 0.74624478 0.62054572 0.55481275] [ 0.12808126 0.7430506 -0.18061266 0.52545181] [ 1.54329851 1.01027268 -0.22230215 -1.61514339] [-0.59584811 -1.59336141 -1.06984676 0.37731361]]
In [130]:
# location
# loc
df.loc['2023-08-04':'2023-08-06', 'A':'C'] # loc 명령어가 없으면 error 발생
Out[130]:
A | B | C | |
---|---|---|---|
2023-08-04 | -0.225068 | 0.744492 | -1.402024 |
2023-08-05 | 0.386276 | 0.283264 | 0.845932 |
2023-08-06 | -0.763337 | 0.746245 | 0.620546 |
In [131]:
# int location
# iloc
df.iloc[0:2, 1:3]
Out[131]:
B | C | |
---|---|---|
2023-08-04 | 0.744492 | -1.402024 |
2023-08-05 | 0.283264 | 0.845932 |
In [132]:
# 데이터 정렬
# sort_values()
df.sort_values(by='A', ascending = True) # True 오름차순, False 내림차순
Out[132]:
A | B | C | D | |
---|---|---|---|---|
2023-08-06 | -0.763337 | 0.746245 | 0.620546 | 0.554813 |
2023-08-09 | -0.595848 | -1.593361 | -1.069847 | 0.377314 |
2023-08-04 | -0.225068 | 0.744492 | -1.402024 | -1.286209 |
2023-08-07 | 0.128081 | 0.743051 | -0.180613 | 0.525452 |
2023-08-05 | 0.386276 | 0.283264 | 0.845932 | -0.284644 |
2023-08-08 | 1.543299 | 1.010273 | -0.222302 | -1.615143 |
In [133]:
df.sort_values(by=['A', 'B'], ascending = True) # True 오름차순, False 내림차순
Out[133]:
A | B | C | D | |
---|---|---|---|---|
2023-08-06 | -0.763337 | 0.746245 | 0.620546 | 0.554813 |
2023-08-09 | -0.595848 | -1.593361 | -1.069847 | 0.377314 |
2023-08-04 | -0.225068 | 0.744492 | -1.402024 | -1.286209 |
2023-08-07 | 0.128081 | 0.743051 | -0.180613 | 0.525452 |
2023-08-05 | 0.386276 | 0.283264 | 0.845932 | -0.284644 |
2023-08-08 | 1.543299 | 1.010273 | -0.222302 | -1.615143 |
In [134]:
# 데이터를 딕셔너리의 리스트로 생성
data = {
'A' : [1, 2, 3, 4, 5],
'B' : [3, 2, 3, 1, 2],
'C' : [5, 4, 3, 2, 1]
}
pd.DataFrame(data)
Out[134]:
A | B | C | |
---|---|---|---|
0 | 1 | 3 | 5 |
1 | 2 | 2 | 4 |
2 | 3 | 3 | 3 |
3 | 4 | 1 | 2 |
4 | 5 | 2 | 1 |
In [135]:
# 데이터를 리스트의 딕셔너리로 생성
data = [
{'A': 1, 'B': 3, 'C': 5},
{'A': 2, 'B': 2, 'C': 4},
{'A': 3, 'B': 3, 'C': 3},
{'A': 4, 'B': 1, 'C': 2},
{'A': 5, 'B': 2, 'C': 1}
]
sort_study_df = pd.DataFrame(data)
In [136]:
sort_study_df.sort_values(by=['B', 'C'])
Out[136]:
A | B | C | |
---|---|---|---|
3 | 4 | 1 | 2 |
4 | 5 | 2 | 1 |
1 | 2 | 2 | 4 |
2 | 3 | 3 | 3 |
0 | 1 | 3 | 5 |
In [137]:
# 컬럼 추가
# 기존의 컬럼이 없으면 추가, 동일한 컬럼이 있으면 덮어쓰기
df['E'] = ['one', 'one', 'two', 'three', 'four', 'seven']
df
Out[137]:
A | B | C | D | E | |
---|---|---|---|---|---|
2023-08-04 | -0.225068 | 0.744492 | -1.402024 | -1.286209 | one |
2023-08-05 | 0.386276 | 0.283264 | 0.845932 | -0.284644 | one |
2023-08-06 | -0.763337 | 0.746245 | 0.620546 | 0.554813 | two |
2023-08-07 | 0.128081 | 0.743051 | -0.180613 | 0.525452 | three |
2023-08-08 | 1.543299 | 1.010273 | -0.222302 | -1.615143 | four |
2023-08-09 | -0.595848 | -1.593361 | -1.069847 | 0.377314 | seven |
In [138]:
# 데이터 삭제
# axis=1 세로, aixs=0 가로
# inplace: 내부 내용을 바꾼다
df.drop('A', axis = 1, inplace = True)
In [139]:
df
Out[139]:
B | C | D | E | |
---|---|---|---|---|
2023-08-04 | 0.744492 | -1.402024 | -1.286209 | one |
2023-08-05 | 0.283264 | 0.845932 | -0.284644 | one |
2023-08-06 | 0.746245 | 0.620546 | 0.554813 | two |
2023-08-07 | 0.743051 | -0.180613 | 0.525452 | three |
2023-08-08 | 1.010273 | -0.222302 | -1.615143 | four |
2023-08-09 | -1.593361 | -1.069847 | 0.377314 | seven |
In [140]:
df.drop(['2023-08-06', '2023-08-09'], axis=0)
Out[140]:
B | C | D | E | |
---|---|---|---|---|
2023-08-04 | 0.744492 | -1.402024 | -1.286209 | one |
2023-08-05 | 0.283264 | 0.845932 | -0.284644 | one |
2023-08-07 | 0.743051 | -0.180613 | 0.525452 | three |
2023-08-08 | 1.010273 | -0.222302 | -1.615143 | four |
In [141]:
df.drop(columns=['B', 'D'])
Out[141]:
C | E | |
---|---|---|
2023-08-04 | -1.402024 | one |
2023-08-05 | 0.845932 | one |
2023-08-06 | 0.620546 | two |
2023-08-07 | -0.180613 | three |
2023-08-08 | -0.222302 | four |
2023-08-09 | -1.069847 | seven |
In [142]:
df.drop(['2023-08-06'])
Out[142]:
B | C | D | E | |
---|---|---|---|---|
2023-08-04 | 0.744492 | -1.402024 | -1.286209 | one |
2023-08-05 | 0.283264 | 0.845932 | -0.284644 | one |
2023-08-07 | 0.743051 | -0.180613 | 0.525452 | three |
2023-08-08 | 1.010273 | -0.222302 | -1.615143 | four |
2023-08-09 | -1.593361 | -1.069847 | 0.377314 | seven |
In [143]:
df.drop(columns=['E'], inplace = True)
df
Out[143]:
B | C | D | |
---|---|---|---|
2023-08-04 | 0.744492 | -1.402024 | -1.286209 |
2023-08-05 | 0.283264 | 0.845932 | -0.284644 |
2023-08-06 | 0.746245 | 0.620546 | 0.554813 |
2023-08-07 | 0.743051 | -0.180613 | 0.525452 |
2023-08-08 | 1.010273 | -0.222302 | -1.615143 |
2023-08-09 | -1.593361 | -1.069847 | 0.377314 |
In [147]:
def plus_minus(values):
return 'plus' if values > 0 else 'minus'
df['B'] = df['B'].apply(plus_minus)
df
Out[147]:
B | C | D | |
---|---|---|---|
2023-08-04 | plus | -1.402024 | -1.286209 |
2023-08-05 | plus | 0.845932 | -0.284644 |
2023-08-06 | plus | 0.620546 | 0.554813 |
2023-08-07 | plus | -0.180613 | 0.525452 |
2023-08-08 | plus | -0.222302 | -1.615143 |
2023-08-09 | minus | -1.069847 | 0.377314 |
In [150]:
# 특정 값 수정
# loc
# iloc
df.loc['2023-08-06', 'C'] = 0.000000
df.iloc[0, 2] = 9.999999
df
Out[150]:
B | C | D | |
---|---|---|---|
2023-08-04 | plus | -1.402024 | 9.999999 |
2023-08-05 | plus | 0.845932 | -0.284644 |
2023-08-06 | plus | 0.000000 | 0.554813 |
2023-08-07 | plus | -0.180613 | 0.525452 |
2023-08-08 | plus | -0.222302 | -1.615143 |
2023-08-09 | minus | -1.069847 | 0.377314 |
In [154]:
# left_df
# key 라는 이름의 컬럼
# key 컬럼의 값으로는 K0, K4, K2, K3
# A 라는 이름의 컬럼
# A 컬럼의 값으로는 A0, A1, A2, A3
# B 라는 이름의 컬럼
# B 컬럼의 값으로는 B0, B1, B2, B3
# list의 dict로 만들어 보세요
left_data = {
'key': ['K0', 'K4', 'K2', 'K3'],
'A': ['A0', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3']
}
left_df = pd.DataFrame(left_data)
left_df
Out[154]:
key | A | B | |
---|---|---|---|
0 | K0 | A0 | B0 |
1 | K4 | A1 | B1 |
2 | K2 | A2 | B2 |
3 | K3 | A3 | B3 |
In [155]:
# right_df
# key 라는 이름의 컬럼
# key 컬럼의 값으로는 K0, K1, K2, K3
# C 라는 이름의 컬럼
# C 컬럼의 값으로는 C0, C1, C2, C3
# D 라는 이름의 컬럼
# D 컬럼의 값으로는 D0, D1, D2, D3
# dict의 list로 만들어 보세요
right_data = [
{'key': 'K0', 'C': 'C0', 'D': 'D0'},
{'key': 'K1', 'C': 'C1', 'D': 'D1'},
{'key': 'K2', 'C': 'C2', 'D': 'D2'},
{'key': 'K3', 'C': 'C3', 'D': 'D3'}
]
right_df = pd.DataFrame(right_data)
right_df
Out[155]:
key | C | D | |
---|---|---|---|
0 | K0 | C0 | D0 |
1 | K1 | C1 | D1 |
2 | K2 | C2 | D2 |
3 | K3 | C3 | D3 |
In [156]:
# merge
# 데이터 프래임을 가로로 병합
pd.merge(left_df, right_df, on='key')
Out[156]:
key | A | B | C | D | |
---|---|---|---|---|---|
0 | K0 | A0 | B0 | C0 | D0 |
1 | K2 | A2 | B2 | C2 | D2 |
2 | K3 | A3 | B3 | C3 | D3 |
In [158]:
# 두 데이터 프래임의 합집합으로 병합
pd.merge(left_df, right_df, on='key', how='outer')
Out[158]:
key | A | B | C | D | |
---|---|---|---|---|---|
0 | K0 | A0 | B0 | C0 | D0 |
1 | K4 | A1 | B1 | NaN | NaN |
2 | K2 | A2 | B2 | C2 | D2 |
3 | K3 | A3 | B3 | C3 | D3 |
4 | K1 | NaN | NaN | C1 | D1 |
In [162]:
# concat
# 세로로 병합
# NaN : Not a Number (누락값)
nan_df = pd.concat([left_df, right_df])
nan_df
Out[162]:
key | A | B | C | D | |
---|---|---|---|---|---|
0 | K0 | A0 | B0 | NaN | NaN |
1 | K4 | A1 | B1 | NaN | NaN |
2 | K2 | A2 | B2 | NaN | NaN |
3 | K3 | A3 | B3 | NaN | NaN |
0 | K0 | NaN | NaN | C0 | D0 |
1 | K1 | NaN | NaN | C1 | D1 |
2 | K2 | NaN | NaN | C2 | D2 |
3 | K3 | NaN | NaN | C3 | D3 |
In [165]:
# NaN 값을 삭제
nan_df.dropna()
Out[165]:
key | A | B | C | D |
---|
In [168]:
# NaN 값을 대체
nan_df.fillna(0) # NaN을 0으로 대체
Out[168]:
key | A | B | C | D | |
---|---|---|---|---|---|
0 | K0 | A0 | B0 | 0 | 0 |
1 | K4 | A1 | B1 | 0 | 0 |
2 | K2 | A2 | B2 | 0 | 0 |
3 | K3 | A3 | B3 | 0 | 0 |
0 | K0 | 0 | 0 | C0 | D0 |
1 | K1 | 0 | 0 | C1 | D1 |
2 | K2 | 0 | 0 | C2 | D2 |
3 | K3 | 0 | 0 | C3 | D3 |
'Data Analysis > Pandas' 카테고리의 다른 글
[Python] [Data Analysis] Pandas를 활용한 서울시 범죄 데이터 전처리 (1) | 2023.08.08 |
---|---|
[Python] [Data Analysis] Pandas DataFrame 가지고 놀기 (1) | 2023.08.07 |
[Python] [Data Analysis] Numpy 기초 (1) | 2023.08.04 |