파이썬
1. 정보 추출 함수
1-1. DataFrame의 상/하위 n개 데이터 추출 : .head() / .tail()
외부 데이터가 잘 추출됐는지 확인 용도, 기본 값은 5개
df = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=['A', 'B', 'C', 'D'])
df.head()
df.head(3)
df.tail()
df.tail(2)
#결과
'''
A B C D
2021-12-08 -1.208131 -2.194505 -0.592236 0.080834
2021-12-09 -1.195402 -0.327135 -1.630431 1.326106
2021-12-10 0.111884 3.096611 -0.282745 0.513996
2021-12-11 1.032994 -1.051557 1.020307 1.172119
2021-12-12 0.223649 0.167089 -0.991968 1.080597
.
.
.
'''
1-2. DataFrame의 index 추출 : .index
df.index
#결과
'''
DatetimeIndex(['2021-12-08', '2021-12-09', '2021-12-10', '2021-12-11', '2021-12-12',
'2021-12-13'], dtype='datetime64[ns]', freq='D')
'''
1-3. DataFrame의 열 이름 추출 : .columns
df.columns
df.columns
#결과
'''
Index(['A', 'B', 'C', 'D'], dtype='object')
'''
1-4. DataFrame의 데이터 추출 : .values
df.values
#결과
'''
array([[-1.20813136, -2.19450481, -0.59223586, 0.08083421],
[-1.19540232, -0.32713473, -1.63043123, 1.32610628],
[ 0.11188354, 3.09661086, -0.28274477, 0.51399573],
[ 1.03299367, -1.05155713, 1.02030745, 1.17211909],
[ 0.22364942, 0.16708882, -0.99196838, 1.08059654],
[ 0.992869 , -1.63620388, 0.35790354, -1.77796449]])
'''
1-5. DataFrame의 전체 정보 추출 : .info()
데이터 안에 null값이 있는지 확인 가능
df.info()
#결과
'''
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 6 entries, 2021-12-08 to 2021-12-13
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
'''
1-5. DataFrame의 통계 요약 : .describe()
df.describe()
#결과
'''
A B C D
count 6.000000 6.000000 6.000000 6.000000
mean -0.007023 -0.324283 -0.353195 0.399281
std 1.000367 1.881051 0.948012 1.164083
min -1.208131 -2.194505 -1.630431 -1.777964
25% -0.868581 -1.490042 -0.892035 0.189125
50% 0.167766 -0.689346 -0.437490 0.797296
75% 0.800564 0.043533 0.197741 1.149238
max 1.032994 3.096611 1.020307 1.326106
'''
2. 데이터 정렬 함수
2-1. DataFrame의 특정 열 기준으로 데이터 정렬 : .sort_values(by=기준 열, ascending=True/False)
df.sort_values(by='B', ascending=False)
df.sort_values(by='B', ascending=True)
#결과
'''
A B C D
2021-12-10 0.111884 3.096611 -0.282745 0.513996
2021-12-12 0.223649 0.167089 -0.991968 1.080597
2021-12-09 -1.195402 -0.327135 -1.630431 1.326106
2021-12-11 1.032994 -1.051557 1.020307 1.172119
2021-12-13 0.992869 -1.636204 0.357904 -1.777964
2021-12-08 -1.208131 -2.194505 -0.592236 0.080834
A B C D
2021-12-08 -1.208131 -2.194505 -0.592236 0.080834
2021-12-13 0.992869 -1.636204 0.357904 -1.777964
2021-12-11 1.032994 -1.051557 1.020307 1.172119
2021-12-09 -1.195402 -0.327135 -1.630431 1.326106
2021-12-12 0.223649 0.167089 -0.991968 1.080597
2021-12-10 0.111884 3.096611 -0.282745 0.513996
'''
2-2. DataFrame의 index 기준으로 데이터 정렬 : .sort_index(ascending=True/False)
df.sort_index(ascending=False)
#결과
'''
A B C D
2021-12-13 0.992869 -1.636204 0.357904 -1.777964
2021-12-12 0.223649 0.167089 -0.991968 1.080597
2021-12-11 1.032994 -1.051557 1.020307 1.172119
2021-12-10 0.111884 3.096611 -0.282745 0.513996
2021-12-09 -1.195402 -0.327135 -1.630431 1.326106
2021-12-08 -1.208131 -2.194505 -0.592236 0.080834
'''
3. 데이터 추출 함수
3-1. DataFrame의 index와 열 이름으로 데이터 추출
#DataFrame의 열 이름으로 데이터 추출 : DataFrame[열 이름]
df['A']
#결과
'''
2021-12-08 -1.208131
2021-12-09 -1.195402
2021-12-10 0.111884
2021-12-11 1.032994
2021-12-12 0.223649
2021-12-13 0.992869
Freq: D, Name: A, dtype: float64
'''
#DataFrame의 내부 index로 데이터 추출 : DataFrame[시작index : 끝index]
df[0 : 3]
#결과
'''
A B C D
2021-12-08 -1.208131 -2.194505 -0.592236 0.080834
2021-12-09 -1.195402 -0.327135 -1.630431 1.326106
2021-12-10 0.111884 3.096611 -0.282745 0.513996
'''
#DataFrame의 index 이름으로 데이터 추출 : DataFrame[시작index이름 : 끝index이름]
df['2021-12-08' : '2021-12-13']
#결과
'''
A B C D
2021-12-08 -1.208131 -2.194505 -0.592236 0.080834
2021-12-09 -1.195402 -0.327135 -1.630431 1.326106
2021-12-10 0.111884 3.096611 -0.282745 0.513996
2021-12-11 1.032994 -1.051557 1.020307 1.172119
2021-12-12 0.223649 0.167089 -0.991968 1.080597
2021-12-13 0.992869 -1.636204 0.357904 -1.777964
'''
#DataFrame의 열 이름과 index 이름으로 데이터 추출 : DataFrame.loc[시작index이름 : 끝index이름, [열 이름, 열 이름]]
df.loc['2021-12-08' : '2021-12-10', ['A', 'B']]
#결과
'''
A B
2021-12-08 -1.208131 -2.194505
2021-12-09 -1.195402 -0.327135
2021-12-10 0.111884 3.096611
'''
3-2. 비교 연산자를 사용해 데이터 추출 : DataFrame[DataFrame.열이름 비교연산 비교값]
#A열의 값이 0보다 큰 모든 열과 행의 값
df[df.A > 0]
#결과
'''
A B C D
2021-12-10 0.111884 3.096611 -0.282745 0.513996
2021-12-11 1.032994 -1.051557 1.020307 1.172119
2021-12-12 0.223649 0.167089 -0.991968 1.080597
2021-12-13 0.992869 -1.636204 0.357904 -1.777964
'''
3-3. DataFrame 복사 : 복사된DataFrame이름 = 기존DataFrame이름.copy()
df2 = df.copy()
3-4. DataFrame에 새로운 열과 데이터 추가 : DataFrame[새 열 이름] = [신규 데이터]
df2['E'] = ['one', 'two', 'three', 'four', 'one', 'two']
#결과
'''
A B C D E
2021-12-08 -1.208131 -2.194505 -0.592236 0.080834 one
2021-12-09 -1.195402 -0.327135 -1.630431 1.326106 two
2021-12-10 0.111884 3.096611 -0.282745 0.513996 three
2021-12-11 1.032994 -1.051557 1.020307 1.172119 four
2021-12-12 0.223649 0.167089 -0.991968 1.080597 one
2021-12-13 0.992869 -1.636204 0.357904 -1.777964 two
'''
3-5. DataFrame의 특정 열에 지정 데이터가 포함 여부 True / False로 산출 :
DataFrame[DataFrame['특정 열']].isin(['조회 값1', '조회 값2' ... '조회 값n'])
df2['E'].isin(['two', 'three'])
#결과
'''
2021-12-08 False
2021-12-09 True
2021-12-10 True
2021-12-11 False
2021-12-12 False
2021-12-13 True
Freq: D, Name: E, dtype: bool
'''
4. DataFrame 연결
4-1. 여러 DataFrame을 차례로 연결해 새로운 DataFrame 생성 : .concat()
새DataFrame이름 = Pandas.concat([DataFrame1, DataFrame2 ... DataFrameN])
df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3'],
'C': ['C0', 'C1', 'C2', 'C3'],
'D': ['D0', 'D1', 'D2', 'D3']}, index=[0, 1, 2, 3])
df2 = pd.DataFrame({'A': ['A4', 'A5', 'A6', 'A7'],
'B': ['B4', 'B5', 'B6', 'B7'],
'C': ['C4', 'C5', 'C6', 'C7'],
'D': ['D4', 'D5', 'D6', 'D7']}, index=[4, 5, 6, 7])
df3 = pd.DataFrame({'A': ['A8', 'A9', 'A10', 'A11'],
'B': ['B8', 'B9', 'B10', 'B11'],
'C': ['C8', 'C9', 'C10', 'C11'],
'D': ['D8', 'D9', 'D10', 'D11']}, index=[8, 9, 10, 11])
result = pd.concat([df1, df2, df3])
#결과
'''
A B C D
0 A0 B0 C0 D0
1 A1 B1 C1 D1
2 A2 B2 C2 D2
3 A3 B3 C3 D3
4 A4 B4 C4 D4
5 A5 B5 C5 D5
6 A6 B6 C6 D6
7 A7 B7 C7 D7
8 A8 B8 C8 D8
9 A9 B9 C9 D9
10 A10 B10 C10 D10
11 A11 B11 C11 D11
'''
4-2. DataFrame 연결 시 레벨에 해당하는 key 부여 : keys = [list]
dfs = pd.concat([df1, df2, df3], keys=['x', 'y', 'z'])
#결과
'''
A B C D
x 0 A0 B0 C0 D0
x 1 A1 B1 C1 D1
x 2 A2 B2 C2 D2
x 3 A3 B3 C3 D3
y 4 A4 B4 C4 D4
y 5 A5 B5 C5 D5
y 6 A6 B6 C6 D6
y 7 A7 B7 C7 D7
z 8 A8 B8 C8 D8
z 9 A9 B9 C9 D9
z 10 A10 B10 C10 D10
z 11 A11 B11 C11 D11
'''
4-3. 행으로 데이터 연결 : 열 이름 기준
df4 = pd.DataFrame({'B': ['B2', 'B3', 'B6', 'B7'],
'D': ['C2', 'C3', 'C6', 'C7'],
'F': ['D2', 'D3', 'D6', 'D7']}, index=[2, 3, 6, 7])
df14 = pd.concat([df1, df4])
#결과
'''
A B C D F
0 A0 B0 C0 D0 NaN
1 A1 B1 C1 D1 NaN
2 A2 B2 C2 D2 NaN
3 A3 B3 C3 D3 NaN
2 NaN B2 NaN C2 D2
3 NaN B3 NaN C3 D3
6 NaN B6 NaN C6 D6
7 NaN B7 NaN C7 D7
'''
key 값이 동일한 열에 차례로 연결, 기본값이 axis=0으로 생략 가능.
4-4. 열로 데이터 연결 : index 기준
df14s = pd.concat([df1, df4], axis=1)
#결과
'''
A B C D B D F
0 A0 B0 C0 D0 NaN NaN NaN
1 A1 B1 C1 D1 NaN NaN NaN
2 A2 B2 C2 D2 B2 C2 D2
3 A3 B3 C3 D3 B3 C3 D3
6 NaN NaN NaN NaN B6 C6 D6
7 NaN NaN NaN NaN B7 C7 D7
'''
idex 이름이 동일한 행에 차례로연결, axis=1.
4-5. 행으로 데이터 연결 : 공통 열 기준
df14s0 = pd.concat([df1, df4], join='inner')
#결과
'''
B D
0 B0 D0
1 B1 D1
2 B2 D2
3 B3 D3
2 B2 C2
3 B3 C3
6 B6 C6
7 B7 C7
'''
4-6. 열로 데이터 연결 : 공통 행 기준
df14s1 = pd.concat([df1, df4], axis=1, join='inner')
#결과
'''
A B C D B D F
2 A2 B2 C2 D2 B2 C2 D2
3 A3 B3 C3 D3 B3 C3 D3
'''
4-7. 새로운 index 부여해 연결 : ignore_index=True
df140i = pd.concat([df1, df4])
#결과
'''
A B C D F
0 A0 B0 C0 D0 NaN
1 A1 B1 C1 D1 NaN
2 A2 B2 C2 D2 NaN
3 A3 B3 C3 D3 NaN
2 NaN B2 NaN C2 D2
3 NaN B3 NaN C3 D3
6 NaN B6 NaN C6 D6
7 NaN B7 NaN C7 D7
'''
df140i = pd.concat([df1, df4], ignore_index=True)
#결과
'''
A B C D F
0 A0 B0 C0 D0 NaN
1 A1 B1 C1 D1 NaN
2 A2 B2 C2 D2 NaN
3 A3 B3 C3 D3 NaN
4 NaN B2 NaN C2 D2
5 NaN B3 NaN C3 D3
6 NaN B6 NaN C6 D6
7 NaN B7 NaN C7 D7
'''
5. DataFrame 병합
5-1. 여러 DataFrame을 병합해 새로운 DataFrame 생성
Pandas.merge(DataFrame1, DataFrame2, on='key이름', how='병합방식')
a = pd.DataFrame({'key': ['K0', 'K4', 'K2', 'K3'],
'A': ['A0', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3']})
b = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3'],
'C': ['C0', 'C1', 'C2', 'C3'],
'D': ['D0', 'D1', 'D2', 'D3']})
pd.merge(a, b, on='key')
#결과
'''
key A B
0 K0 A0 B0
1 K4 A1 B1
2 K2 A2 B2
3 K3 A3 B3
key C D
0 K0 C0 D0
1 K1 C1 D1
2 K2 C2 D2
3 K3 C3 D3
key A B C D
0 K0 A0 B0 C0 D0
1 K2 A2 B2 C2 D2
2 K3 A3 B3 C3 D3
'''
on으로 지정된 열의 값이 병합하려는 DataFrame의 동일 열의 값과 일치하는 행 기준으로만 병합.
how의 기본 값은 inner로 생략 가능.
5-2. how='left' : 왼쪽 DataFrame 기준, 해당 열에
a = pd.DataFrame({'key': ['K0', 'K4', 'K2', 'K3'],
'A': ['A0', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3']})
b = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3'],
'C': ['C0', 'C1', 'C2', 'C3'],
'D': ['D0', 'D1', 'D2', 'D3']})
pd.merge(a, b, on='key', how='left')
#결과
'''
key A B
0 K0 A0 B0
1 K4 A1 B1
2 K2 A2 B2
3 K3 A3 B3
key C D
0 K0 C0 D0
1 K1 C1 D1
2 K2 C2 D2
3 K3 C3 D3
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
'''
left에 있는 전체 열의 모든 값을 놓고 on으로 지정된 열의 값 기준으로 병합.
일치하면 값을 입력, 일치하지 않으면 NaN으로 대체.
5-3. how='right' : 오른쪽 DataFrame 기준,
pd.merge(a, b, on='key', how='right')
#결과
'''
key A B
0 K0 A0 B0
1 K4 A1 B1
2 K2 A2 B2
3 K3 A3 B3
key C D
0 K0 C0 D0
1 K1 C1 D1
2 K2 C2 D2
3 K3 C3 D3
key A B C D
0 K0 A0 B0 C0 D0
1 K1 NaN NaN C1 D1
2 K2 A2 B2 C2 D2
3 K3 A3 B3 C3 D3
'''
right에 있는 전체 열의 모든 값을 놓고 on으로 지정된 열의 값 기준으로 병합.
일치하면 값을 입력, 일치하지 않으면 NaN으로 대체.
6. 외부 파일을 DataFrame으로 읽어 오기
6-1. pandas.read_csv('파일경로') / pandas.read_excel('파일경로')
DataFrame = pd.read_csv('./data/csv/weather.csv', encoding='euc-kr')
#결과
'''
일시 평균기온(°C) 최대 풍속(m/s) 평균 풍속(m/s)
0 2010-08-01 28.7 8.3 3.4
1 2010-08-02 25.2 8.7 3.8
2 2010-08-03 22.1 6.3 2.9
3 2010-08-04 25.3 6.6 4.2
4 2010-08-05 27.2 9.1 5.6
... ... ... ...
3648 2020-07-27 22.1 4.2 1.7
3649 2020-07-28 21.9 4.5 1.6
3650 2020-07-29 21.6 3.2 1.0
3651 2020-07-30 22.9 9.7 2.4
3652 2020-07-31 25.7 4.8 2.5
[3653 rows x 4 columns]
'''
6-2. 특정 열을 index로 지정해 파일 읽어 오기 : index_col=index로 지정할 열의 순서(번호)
df_my_index = pd.read_csv('./data/csv/countries.csv', encoding='euc-kr', index_col=0)
Pandas의 .read_csv()함수는 파일의 첫번째 행을 각 Series의 열 이름으로 자동 설정 후,
각 행에 대한 index는 0으로 시작하는 정수의 나열로 자동 생성.
index_col=을 사용하면 특정 열을 자체를 index로 사용할 수 있음.
6-3. 한글 및 영문 encoding 오류 해결 : encoding='cp949', 'utf-8', 'euc-kr'
6-4. 특정 데이터 선택
#열 이름 이용 : DataFrame['열 이름']
df_my_index['country']
#결과
'''
KR Korea
US USA
JP Japan
CN China
RU Russia
Name: country, dtype: object
'''
#각 열의 이름을 list로 설정해 다중 열 선택 : DataFrame[['열 이름', '열 이름' ...]]
df_my_index[['country', 'capital']]
#결과
'''
country capital
KR Korea Seoul
US USA Washington
JP Japan Tokyo
CN China Beijing
RU Russia Moscow
'''
#슬라이싱을 이용한 행 선택 : DataFrame[ : ]
df_my_index[:3]
#결과
'''
country area capital population
KR Korea 98480 Seoul 51780579
US USA 9629091 Washington 331002825
JP Japan 377835 Tokyo 125960000
'''
#특정 record 한개만 선택 : DataFrame.loc['행', '열']
df_my_index.loc['US', 'capital']
#결과
'''
'Washington'
'''
#특정 열의 특정 행 선택 : DataFrame['열'][행index번호]
df_my_index['capital'][1]
#결과
'''
'Washington'
'''
#특정 열의 다중 행 선택 : DataFrame['열'][행index번호슬라이싱]
df_my_index['capital'][:3]
#결과
'''
KR Seoul
US Washington
JP Tokyo
Name: capital, dtype: object
'''
6-5. 각 열을 연산 처리 후, 새로운 열로 생성 : DataFrame['새로운 열 이름'] = 새로운 데이터
#df_my_index에 인구밀도를 나타내는 'density' 열 추가 : 인구밀도 = 인구/면적
df_my_index['density'] = df_my_index['population']/df_my_index['area']
#결과
'''
KR 525.797918
US 34.375293
JP 333.373033
CN 149.977044
RU 8.581789
Name: density, dtype: float64
'''
df_my_index['population']/df_my_index['area']와 같이 DataFrame의 어떤 열이 다른 열의 값에 의해 결정될 때,
행 별로 반복하여 연산하는 것이 아니라 필요한 열에 통째로 접근하여 한꺼번에 처리.
6-6. 표준편차 산출 : .std()
#pandas 이용
import numpy as np
pandas_std = df_my_index['평균기온'].std()
#결과
'''
579579005.3714743
'''
#numpy 이용
import numpy as np
numpy_std = np.std(df_my_index['평균기온'])
#결과
'''
518391221.7369328
'''
pandas와 numpy는 계산 방식이 달라, 동일한 데이터의 산출 값이 차이 남.
'LG U+ why not SW 5 > python' 카테고리의 다른 글
파이썬 데이터 분석 _ 결측치 처리 및 boxplot으로 이상치 처리 (0) | 2025.03.04 |
---|---|
파이썬 데이터 분석 _ matplot 라이브러리의 plot함수 기본 정리 (0) | 2025.03.03 |
파이썬 데이터 분석 _ pandas 라이브러리 활용 2 : numpy (0) | 2025.03.02 |
파이썬 데이터 분석 _ pandas 라이브러리 활용 1 : Series / DataFrame (0) | 2025.03.02 |
파이썬 데이터 분석 _ 라이브러리 모음 (0) | 2025.03.02 |