| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 |
- 머신러닝
- Python crawler
- pandas
- Titanic data set
- 판다스
- K평균군집화
- 파이썬 제어문
- Naive Bayes
- 제어문
- 넘파이
- 타이타닉 데이터
- 나이브베이즈
- 파이썬 크롤러
- 사이킷런
- ML
- sklearn
- python control statement
- NumPy
- dataframe
- KMeans Clustering
- scikit-learn
- python
- Machine Learning
- 순회 크롤러
- Data pre-processing
- 파이썬 크롤링
- 배열
- 파이썬
- control statement
- 파이썬 객체 지향 프로그래밍
- Today
- Total
Try to 개발자 EthanJ의 성장 로그
Pandas DataFrame 판다스 데이터프레임 본문
Pandas DataFrame 판다스 데이터프레임¶
DataFrame¶
2차원 배열과 유사한 자료형
다차원
list,dict자료형으로 데이터 구성 가능Similar data structure with relational database
table, MS excel.xlsx,.csvfile하나의
column= 하나의Series= 하나의row하나의
Dataframe= 한 개 이상의Series묶음
index 특징
row index: 행 인덱스:
axis=0- RangeIndex
int index대신 지정한label index사용해도,int index병행 사용 가능
- RangeIndex
column index: 열 인덱스:
axis=1- 지정
label index사용 시, RangeIndexint index사용 불가
- 지정
import pandas as pd
import numpy as np
1. DataFrame 생성¶
pd.DataFrame(data)data:
다차원 list,dict다차원 list: item length 동일, 서로 다른 dtype 가능dict: item length 동일, 서로 다른 dtype 가능- 주의사항: data type에 따라서 item length issue breakouts
DataFrame의cell(tuple): 모든 data type 및 다양한 data type 혼합 가능- 각
axis별 length 동일해야 함
- 각
- 2-dim list (3 row, 4 columns):
label index미지정 > RangeIndexint index자동 생성
list_2dim = [[1, 2, 3.5, 4],
['a', 'b', 'c', 'd'],
[0.1, 3, 0.5, 8]]
df_2dim = pd.DataFrame(list_2dim)
df_2dim
| 0 | 1 | 2 | 3 | |
|---|---|---|---|---|
| 0 | 1 | 2 | 3.5 | 4 |
| 1 | a | b | c | d |
| 2 | 0.1 | 3 | 0.5 | 8 |
axis별 length가 다른listmaximum length row를 기준으로
DataFrame구조 생성length가 모자른
cell:NaN으로 filled
len_list = [[1, 2, 3, 4, 5],
['a', 'b'],
[0.1, 0.2, 0.5]]
df_len = pd.DataFrame(len_list)
df_len
| 0 | 1 | 2 | 3 | 4 | |
|---|---|---|---|---|---|
| 0 | 1 | 2 | 3.0 | 4.0 | 5.0 |
| 1 | a | b | NaN | NaN | NaN |
| 2 | 0.1 | 0.2 | 0.5 | NaN | NaN |
dictdata로DataFrame생성dict의keyvalue:DataFrame의columns name으로 자동 지정dict의value내부 item 개수는 standardized 돼야 함
my_dict = {'a':[10, 20, 30, 40],
'b':[1, 2, 3, 4],
'c':[5, 6, 7, 8]}
df_dict = pd.DataFrame(my_dict)
print(type(df_dict))
df_dict
<class 'pandas.core.frame.DataFrame'>
| a | b | c | |
|---|---|---|---|
| 0 | 10 | 1 | 5 |
| 1 | 20 | 2 | 6 |
| 2 | 30 | 3 | 7 |
| 3 | 40 | 4 | 8 |
pd.DataFrame(dict): 각key별 매칭된value의 길이가 모두 동일해야함- 개수가 모자란
cell(tuple)을 가진dict로DataFrame생성: ValueError
- 개수가 모자란
defi_dict = {'a':[10],
'b':[1, 2, 3, 4],
'c':[5, 6, 7]}
defi_dict
{'a': [10], 'b': [1, 2, 3, 4], 'c': [5, 6, 7]}
# defi_df = pd.DataFrame(defi_dict)
# ValueError: All arrays must be of the same length
dict아닌 data type이라도 >row index,columns index지정 가능index지정 DataFrame 생성
:pd.DataFrame()optional parameterindex=[],columns=[]
columns=parameter: columns index name 지정:
> columns 개수와 동일한 length를 가진 list 전달
index=parameter: row index name 지정:
> row 개수와 동일한 length를 가진 list 전달
list_2dim
[[1, 2, 3.5, 4], ['a', 'b', 'c', 'd'], [0.1, 3, 0.5, 8]]
df_index = pd.DataFrame(list_2dim,
index=['r1', 'r2', 'r3'],
columns=['c1', 'c2', 'c3', 'c4'])
df_index
| c1 | c2 | c3 | c4 | |
|---|---|---|---|---|
| r1 | 1 | 2 | 3.5 | 4 |
| r2 | a | b | c | d |
| r3 | 0.1 | 3 | 0.5 | 8 |
dict로DataFrame생성:column(key) 순서 변경,row index지정해서 생성 가능
my_dict
{'a': [10, 20, 30, 40], 'b': [1, 2, 3, 4], 'c': [5, 6, 7, 8]}
df_order = pd.DataFrame(my_dict, index=list('rows'), columns=list('cba'))
df_order
| c | b | a | |
|---|---|---|---|
| r | 5 | 1 | 10 |
| o | 6 | 2 | 20 |
| w | 7 | 3 | 30 |
| s | 8 | 4 | 40 |
parameter
columns=[]: data에 없거나 더 많은 columns namelist전달- 새로운 columns name으로 column 생성,
NaNvalue filled
- 새로운 columns name으로 column 생성,
new_df = pd.DataFrame(my_dict, columns=list('abcd'))
new_df
| a | b | c | d | |
|---|---|---|---|---|
| 0 | 10 | 1 | 5 | NaN |
| 1 | 20 | 2 | 6 | NaN |
| 2 | 30 | 3 | 7 | NaN |
| 3 | 40 | 4 | 8 | NaN |
dictdata row 개수(key별value의 item 개수) $\ne$index=[]list item 개수> Value Error
my_dict
{'a': [10, 20, 30, 40], 'b': [1, 2, 3, 4], 'c': [5, 6, 7, 8]}
# df_item = pd.DataFrame(my_dict, index=list('qwerty'))
# ValueError: Length of values (4) does not match length of index (6)
2. DataFrame 속성¶
속성은 소괄호를 붙이지 않음
df.index: df 객체의 행 인덱스 배열을 반환df.columns: df 객체의 열 인덱스 배열을 반환df.axes: df 객체의 행, 열 인덱스를 아이템으로 가지는 배열을 반환df.values: df 객체의 data(value)를 아이템으로 가지는 2차원 배열을 반환df.dtypes: df 객체의 item data type을 columns 기준으로 반환df.size: df 객체의 item data 개수(길이)를 반환df.shape: df 객체의 shape(axis=0,axis=1, ..., axis=n-1)를 반환df.T: 행과 열이 교환된 DataFrame 반환(transposed)
dicttoDataFrame지역별 연도별 유입 인구
pop_data = {'서울':[150, 180, 300],
'경기':[200, 240, 450],
'충청':[-10, 3, -13],
'경상':[10, 20, 30],
'전라':[5, 6, 7]
}
pop_sample = pd.DataFrame(pop_data)
pop_sample
| 서울 | 경기 | 충청 | 경상 | 전라 | |
|---|---|---|---|---|---|
| 0 | 150 | 200 | -10 | 10 | 5 |
| 1 | 180 | 240 | 3 | 20 | 6 |
| 2 | 300 | 450 | -13 | 30 | 7 |
DataFrame 속성
df.index: df객체의 row index array 반환row index설정: row 개수와 동일한 item 가지는list로 전달
year_list= [2016, 2017, 2018]
pop_sample.index = year_list
pop_sample
| 서울 | 경기 | 충청 | 경상 | 전라 | |
|---|---|---|---|---|---|
| 2016 | 150 | 200 | -10 | 10 | 5 |
| 2017 | 180 | 240 | 3 | 20 | 6 |
| 2018 | 300 | 450 | -13 | 30 | 7 |
row index이름 지정:df.index.name = 'name'
pop_sample.index.name = 'year'
pop_sample
| 서울 | 경기 | 충청 | 경상 | 전라 | |
|---|---|---|---|---|---|
| year | |||||
| 2016 | 150 | 200 | -10 | 10 | 5 |
| 2017 | 180 | 240 | 3 | 20 | 6 |
| 2018 | 300 | 450 | -13 | 30 | 7 |
DataFrame 속성
df.columns:columns index추출
pop_sample.columns
Index(['서울', '경기', '충청', '경상', '전라'], dtype='object')
columns indexidentifier 지정:df.columns.name = 'name'
pop_sample.columns.name = 'location'
pop_sample
| location | 서울 | 경기 | 충청 | 경상 | 전라 |
|---|---|---|---|---|---|
| year | |||||
| 2016 | 150 | 200 | -10 | 10 | 5 |
| 2017 | 180 | 240 | 3 | 20 | 6 |
| 2018 | 300 | 450 | -13 | 30 | 7 |
row index modify
df.index속성값 활용row의 개수와 동일한
list를 전달속성값
df.index로 사용하는 인덱스 객체는 하나의 item만 수정 불가. 전체 전달
pop_sample.index = [1998, 1999, 2000]
pop_sample
| location | 서울 | 경기 | 충청 | 경상 | 전라 |
|---|---|---|---|---|---|
| 1998 | 150 | 200 | -10 | 10 | 5 |
| 1999 | 180 | 240 | 3 | 20 | 6 |
| 2000 | 300 | 450 | -13 | 30 | 7 |
Index modification
DataFrame method:
df.rename(data, axis=0)axis: default:axis=0= row index =df.index- column index에 대한 수정:
axis=1oraxis='columns'
- column index에 대한 수정:
data:
dicttype,{'기존 인덱스명':'바꿀 인덱스명'}optional parameter
inplace=: default:inplace=False: 수행한 결과 반환, 원본 적용 Xinplace=True> 바뀐 결과 바로 적용
pop_sample.rename({1998:1990})
| location | 서울 | 경기 | 충청 | 경상 | 전라 |
|---|---|---|---|---|---|
| 1990 | 150 | 200 | -10 | 10 | 5 |
| 1999 | 180 | 240 | 3 | 20 | 6 |
| 2000 | 300 | 450 | -13 | 30 | 7 |
pop_sample
| location | 서울 | 경기 | 충청 | 경상 | 전라 |
|---|---|---|---|---|---|
| 1998 | 150 | 200 | -10 | 10 | 5 |
| 1999 | 180 | 240 | 3 | 20 | 6 |
| 2000 | 300 | 450 | -13 | 30 | 7 |
열 인덱스(column) 변경:
axis=1oraxis=columnsinplace=False(default): 원본 변경 X
pop_sample.rename({"전라":"제주"}, axis=1)
| location | 서울 | 경기 | 충청 | 경상 | 제주 |
|---|---|---|---|---|---|
| 1998 | 150 | 200 | -10 | 10 | 5 |
| 1999 | 180 | 240 | 3 | 20 | 6 |
| 2000 | 300 | 450 | -13 | 30 | 7 |
DataFrame 속성
df.axes: df 객체의 행, 열 인덱스를 아이템으로 가지는 배열을 반환- return list: 첫 번째 item = row index, 두 번째 item = columns index
pop_sample.axes
[Int64Index([1998, 1999, 2000], dtype='int64'), Index(['서울', '경기', '충청', '경상', '전라'], dtype='object', name='location')]
df.reset_index(drop=False): row index를 일괄 변경optional parameter:
dropdefault
drop=False: 기존 "row index" data > 새로운 cloumn index "index"으로 넘김, RangeIndexint index자동 생성drop=True: 기존 "row index" 삭제, RangeIndexint index자동 생성
pop_sample.reset_index()
| location | index | 서울 | 경기 | 충청 | 경상 | 전라 |
|---|---|---|---|---|---|---|
| 0 | 1998 | 150 | 200 | -10 | 10 | 5 |
| 1 | 1999 | 180 | 240 | 3 | 20 | 6 |
| 2 | 2000 | 300 | 450 | -13 | 30 | 7 |
pop_sample
| location | 서울 | 경기 | 충청 | 경상 | 전라 |
|---|---|---|---|---|---|
| 1998 | 150 | 200 | -10 | 10 | 5 |
| 1999 | 180 | 240 | 3 | 20 | 6 |
| 2000 | 300 | 450 | -13 | 30 | 7 |
pop_sample.reset_index(drop=True)
| location | 서울 | 경기 | 충청 | 경상 | 전라 |
|---|---|---|---|---|---|
| 0 | 150 | 200 | -10 | 10 | 5 |
| 1 | 180 | 240 | 3 | 20 | 6 |
| 2 | 300 | 450 | -13 | 30 | 7 |
pop_sample
| location | 서울 | 경기 | 충청 | 경상 | 전라 |
|---|---|---|---|---|---|
| 1998 | 150 | 200 | -10 | 10 | 5 |
| 1999 | 180 | 240 | 3 | 20 | 6 |
| 2000 | 300 | 450 | -13 | 30 | 7 |
DataFrame 객체 속성
df.values: 객체의 data(value)를 아이템으로 가지는 2차원 array 반환
pop_sample.values
array([[150, 200, -10, 10, 5],
[180, 240, 3, 20, 6],
[300, 450, -13, 30, 7]], dtype=int64)
DataFrame 객체 속성
df.dtypes: df 객체의 item data type을 columns 기준으로 반환
pop_sample.dtypes
location 서울 int64 경기 int64 충청 int64 경상 int64 전라 int64 dtype: object
DataFrame 객체 속성
df.size: df 객체의 item data 개수(길이)를 반환
pop_sample.size
15
len(df): 가장 큰 dimension:axis=0: row단위 개수만 반환
len(pop_sample)
3
DataFrame 객체 속성
df.shape: df 객체의 shape(axis=0,axis=1, ..., axis=n-1)를 반환
pop_sample.shape
(3, 5)
DataFrame 객체 속성
df.T: 행과 열이 교환된 DataFrame 반환(transeposed)
trans_df = pop_sample.T
trans_df
| 1998 | 1999 | 2000 | |
|---|---|---|---|
| location | |||
| 서울 | 150 | 180 | 300 |
| 경기 | 200 | 240 | 450 |
| 충청 | -10 | 3 | -13 |
| 경상 | 10 | 20 | 30 |
| 전라 | 5 | 6 | 7 |
trans_df.index
Index(['서울', '경기', '충청', '경상', '전라'], dtype='object', name='location')
trans_df.columns
Int64Index([1998, 1999, 2000], dtype='int64')
3. 인덱싱(indexing)¶
default: columns indexing: return
Seriesdf[col]df.coldf.get(col)
row indexing
df.iloc[idx]: RangeIndexint indexdf.loc[label]: 지정한label index: 기본 인덱스가 아니면 모두 loc 메소드 사용
- "서울" column 조회 3가지 방법
기본적인 indexing 기호:
df[col_name]df.col_name>col_name이 변수명으로 사용할 수 있을 때만 가능DataFrame method:
df.get(col_name)
pop_sample['서울']
1998 150 1999 180 2000 300 Name: 서울, dtype: int64
pop_sample.서울
1998 150 1999 180 2000 300 Name: 서울, dtype: int64
pop_sample.get("서울")
1998 150 1999 180 2000 300 Name: 서울, dtype: int64
pop_sample
| location | 서울 | 경기 | 충청 | 경상 | 전라 |
|---|---|---|---|---|---|
| 1998 | 150 | 200 | -10 | 10 | 5 |
| 1999 | 180 | 240 | 3 | 20 | 6 |
| 2000 | 300 | 450 | -13 | 30 | 7 |
df.iloc[idx]: idx번째 행(row) 추출df.loc[label_index]:label index에 해당하는 행(row) 추출return value:
SeriesSeriesname: 기존 DataFrame에서 reference한 해당 행의label index
print(type(pop_sample.iloc[0]))
print(pop_sample.iloc[0].name)
pop_sample.iloc[0]
<class 'pandas.core.series.Series'> 1998
location 서울 150 경기 200 충청 -10 경상 10 전라 5 Name: 1998, dtype: int64
label index로 행 조회:df.loc[label_index]
pop_sample.loc[1999]
location 서울 180 경기 240 충청 3 경상 20 전라 6 Name: 1999, dtype: int64
여러개의 columns 조회: list in list로 colname 나열해서 전달
df[[col_name1, col_name2, ...]]: returnDataFrame
pop_sample[['서울', '경기']]
| location | 서울 | 경기 |
|---|---|---|
| 1998 | 150 | 200 |
| 1999 | 180 | 240 |
| 2000 | 300 | 450 |
- 여러 개의 columns + 하나의 row data 추출 > return
Series
pop_sample[['경기', '경상']].loc[1999]
location 경기 240 경상 20 Name: 1999, dtype: int64
pop_sample.loc[1999][['경기', '경상']]
location 경기 240 경상 20 Name: 1999, dtype: int64
- 두 개 이상의 row 조회:
df.loc[[row1, row2, ...]]> returnDataFrame
pop_sample.loc[[1998, 2000]]
| location | 서울 | 경기 | 충청 | 경상 | 전라 |
|---|---|---|---|---|---|
| 1998 | 150 | 200 | -10 | 10 | 5 |
| 2000 | 300 | 450 | -13 | 30 | 7 |
pop_sample.loc[[1998, 2000]]['충청']
1998 -10 2000 -13 Name: 충청, dtype: int64
pop_sample['충청'].loc[[1998, 2000]]
1998 -10 2000 -13 Name: 충청, dtype: int64
2-dim list로 indexing >DataFrame반환
pop_sample['충청']
1998 -10 1999 3 2000 -13 Name: 충청, dtype: int64
pop_sample[['충청']]
| location | 충청 |
|---|---|
| 1998 | -10 |
| 1999 | 3 |
| 2000 | -13 |
pop_sample['충청'].loc[1999]
3
pop_sample[['충청']].loc[[1999]]
| location | 충청 |
|---|---|
| 1999 | 3 |
4. 슬라이싱 slicing¶
row(행) slicing
순서가 있음 > row 단독 slicing 가능
기본 슬라이싱 문법: 기본 RangeIndex
int index를 기준으로 적용int indexslicing: not includingstop indexlabel indexslicing: includingstop index
col(열) slicing
순서가 없음 > column 단독 slicing 불가능
row slicing 결과에 대해:
label indexcolumn slicing 가능:int index불가능label indexslicing만 가능: includingstop index
- row slicing:
df[start:stop:step]
pop_sample[0:2]
| location | 서울 | 경기 | 충청 | 경상 | 전라 |
|---|---|---|---|---|---|
| 1998 | 150 | 200 | -10 | 10 | 5 |
| 1999 | 180 | 240 | 3 | 20 | 6 |
pop_sample[0:3:2]
| location | 서울 | 경기 | 충청 | 경상 | 전라 |
|---|---|---|---|---|---|
| 1998 | 150 | 200 | -10 | 10 | 5 |
| 2000 | 300 | 450 | -13 | 30 | 7 |
pop_sample[:2000]
| location | 서울 | 경기 | 충청 | 경상 | 전라 |
|---|---|---|---|---|---|
| 1998 | 150 | 200 | -10 | 10 | 5 |
| 1999 | 180 | 240 | 3 | 20 | 6 |
| 2000 | 300 | 450 | -13 | 30 | 7 |
pop_sample[::-1]
| location | 서울 | 경기 | 충청 | 경상 | 전라 |
|---|---|---|---|---|---|
| 2000 | 300 | 450 | -13 | 30 | 7 |
| 1999 | 180 | 240 | 3 | 20 | 6 |
| 1998 | 150 | 200 | -10 | 10 | 5 |
columns slicing
row indexing 결과에 columns slicing
df.loc[:, start:stop:step]: RangeIndexint index사용 X,label index만 사용
pop_sample.loc[:, '서울':'경기']
| location | 서울 | 경기 |
|---|---|---|
| 1998 | 150 | 200 |
| 1999 | 180 | 240 |
| 2000 | 300 | 450 |
int indexslicingdf[:stop_column][:stop_row]==df.iloc[:stop_row][:stop_column]
zr_data = np.zeros((4, 4))
zr_data
array([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
zr_df = pd.DataFrame(zr_data)
zr_df
| 0 | 1 | 2 | 3 | |
|---|---|---|---|---|
| 0 | 0.0 | 0.0 | 0.0 | 0.0 |
| 1 | 0.0 | 0.0 | 0.0 | 0.0 |
| 2 | 0.0 | 0.0 | 0.0 | 0.0 |
| 3 | 0.0 | 0.0 | 0.0 | 0.0 |
zr_df[:3][:2]
| 0 | 1 | 2 | 3 | |
|---|---|---|---|---|
| 0 | 0.0 | 0.0 | 0.0 | 0.0 |
| 1 | 0.0 | 0.0 | 0.0 | 0.0 |
zr_df.iloc[:3, :2]
| 0 | 1 | |
|---|---|---|
| 0 | 0.0 | 0.0 |
| 1 | 0.0 | 0.0 |
| 2 | 0.0 | 0.0 |
Col1 = pd.Series([0, 3, 'ks01', 2, 5])
Col2 = pd.Series(["big", "data", "is", "very", "good"])
Col3 = pd.Series([2.7, -5.0, 2.12, 8.31, -1.34])
Col4 = pd.Series([True, True, False, False, True])
col_list = [Col1, Col2, Col3, Col4]
df_prac = pd.DataFrame({'Col1':col_list[0], 'Col2':col_list[1],
'Col3':col_list[2], 'Col4':col_list[3]})
df_prac
| Col1 | Col2 | Col3 | Col4 | |
|---|---|---|---|---|
| 0 | 0 | big | 2.70 | True |
| 1 | 3 | data | -5.00 | True |
| 2 | ks01 | is | 2.12 | False |
| 3 | 2 | very | 8.31 | False |
| 4 | 5 | good | -1.34 | True |
df_prac.index = list("ABCDE")
df_prac
| Col1 | Col2 | Col3 | Col4 | |
|---|---|---|---|---|
| A | 0 | big | 2.70 | True |
| B | 3 | data | -5.00 | True |
| C | ks01 | is | 2.12 | False |
| D | 2 | very | 8.31 | False |
| E | 5 | good | -1.34 | True |
- 'Col1', 'Col3' 함께 추출
df_prac[['Col1', 'Col3']]
| Col1 | Col3 | |
|---|---|---|
| A | 0 | 2.70 |
| B | 3 | -5.00 |
| C | ks01 | 2.12 |
| D | 2 | 8.31 |
| E | 5 | -1.34 |
- row 'A', 'C', 'D' 추출
df_prac.loc[['A', 'C', 'D']]
| Col1 | Col2 | Col3 | Col4 | |
|---|---|---|---|---|
| A | 0 | big | 2.70 | True |
| C | ks01 | is | 2.12 | False |
| D | 2 | very | 8.31 | False |
- row 'B', 'D' > columns 'Col1', 'Col2' 추출
df_prac[['Col1', 'Col2']].loc[['B', 'D']]
| Col1 | Col2 | |
|---|---|---|
| B | 3 | data |
| D | 2 | very |
5. columns, row 추가, 변경¶
columns 추가, 변경: column indexing:
df['column']scalar value
ndarray,list(row개수와 item개수 일치)column 간의 연산 (a col $\pm$ b col = c col)
Seriesobject 전달
row 추가, 변경: row indexing:
df.loc['row']scalar value
ndarray,list,dict(column개수와 item개수 일치)operation between rows
Data analystic에서 row와 column의 의미
column: variable(charateristic)
row: 개체별 data(
record)
전체 데이터를 구성하는 variable(columns)를 추가, 삭제하는 일은 빈번하게 발생하지만,
특정 index를 기준으로 한 row data(record)를 추가, 삭제하는 일은 자주 발생하지 않음.
데이터 처리를 하는 과정에서 record 추가, 삭제는 권장하지 않는 작업.
5.1. columns 추가¶
- 모든 row에 대해서 동일한 value를 가지는 column 추가: scalar value(single value)
df['column'] = scalar value
pop_sample['제주'] = 1
pop_sample
| location | 서울 | 경기 | 충청 | 경상 | 전라 | 제주 |
|---|---|---|---|---|---|---|
| 1998 | 150 | 200 | -10 | 10 | 5 | 1 |
| 1999 | 180 | 240 | 3 | 20 | 6 | 1 |
| 2000 | 300 | 450 | -13 | 30 | 7 | 1 |
- 서로 다른 value의 data로 구성된 column 추가:
df['column'] = list or ndarray
- Condition:
ndarrayorlist의 length는 row length와 일치해야 함
print(len(pop_sample))
pop_sample['부산'] = np.random.randint(1, 10, len(pop_sample))
pop_sample
3
| location | 서울 | 경기 | 충청 | 경상 | 전라 | 제주 | 부산 |
|---|---|---|---|---|---|---|---|
| 1998 | 150 | 200 | -10 | 10 | 5 | 1 | 5 |
| 1999 | 180 | 240 | 3 | 20 | 6 | 1 | 5 |
| 2000 | 300 | 450 | -13 | 30 | 7 | 1 | 2 |
- column간의 연산 결과로 column추가:
파생변수
pop_sample['수도권'] = pop_sample['서울'] + pop_sample['경기']
pop_sample
| location | 서울 | 경기 | 충청 | 경상 | 전라 | 제주 | 부산 | 수도권 |
|---|---|---|---|---|---|---|---|---|
| 1998 | 150 | 200 | -10 | 10 | 5 | 1 | 5 | 350 |
| 1999 | 180 | 240 | 3 | 20 | 6 | 1 | 5 | 420 |
| 2000 | 300 | 450 | -13 | 30 | 7 | 1 | 2 | 750 |
Series object전달
Condition: 대상
DataFrame과 추가할Series의 길이(column item 개수) 파악label index기준:Seriesdata와DataFrame의 data가 mapping반드시 대상
DataFrame의 길이와Series의 길이가 일치하지 않아도 된다.Series에 없는label index:NaNvalue filled`
pop_sr = pd.Series([10, -10], index=[1998, 2000])
pop_sr
1998 10 2000 -10 dtype: int64
pop_sample["강원"] = pop_sr
pop_sample
| location | 서울 | 경기 | 충청 | 경상 | 전라 | 제주 | 부산 | 수도권 | 강원 |
|---|---|---|---|---|---|---|---|---|---|
| 1998 | 150 | 200 | -10 | 10 | 5 | 1 | 5 | 350 | 10.0 |
| 1999 | 180 | 240 | 3 | 20 | 6 | 1 | 5 | 420 | NaN |
| 2000 | 300 | 450 | -13 | 30 | 7 | 1 | 2 | 750 | -10.0 |
- length(data 개수)가 동일해도
label index기준 mapping:Series에 없는 column >NaNfilled
no_label_sr = pd.Series([100, 200, 300])
no_label_sr
0 100 1 200 2 300 dtype: int64
pop_sample['test'] = no_label_sr
pop_sample
| location | 서울 | 경기 | 충청 | 경상 | 전라 | 제주 | 부산 | 수도권 | 강원 | test |
|---|---|---|---|---|---|---|---|---|---|---|
| 1998 | 150 | 200 | -10 | 10 | 5 | 1 | 5 | 350 | 10.0 | NaN |
| 1999 | 180 | 240 | 3 | 20 | 6 | 1 | 5 | 420 | NaN | NaN |
| 2000 | 300 | 450 | -13 | 30 | 7 | 1 | 2 | 750 | -10.0 | NaN |
5.2. row 추가¶
row 추가: row indeing
scalar value
operation between rows
ndarray,list,dict: columns 개수와 item 개수 일치해야 함
row 추가
- scalar value:
df.loc[idx] = scalar: column 추가와 동일
- scalar value:
pop_sample.loc[2001] = 0
pop_sample
| location | 서울 | 경기 | 충청 | 경상 | 전라 | 제주 | 부산 | 수도권 | 강원 | test |
|---|---|---|---|---|---|---|---|---|---|---|
| 1998 | 150 | 200 | -10 | 10 | 5 | 1 | 5 | 350 | 10.0 | NaN |
| 1999 | 180 | 240 | 3 | 20 | 6 | 1 | 5 | 420 | NaN | NaN |
| 2000 | 300 | 450 | -13 | 30 | 7 | 1 | 2 | 750 | -10.0 | NaN |
| 2001 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.0 | 0.0 |
pop_sample.shape
(4, 10)
row 추가
data value:
ndarry,list,dictdata type- column 개수와 data item 개수 일치
ndarray로 추가
pop_sample.loc[2002] = np.random.randint(-100, 100, 10)
pop_sample
| location | 서울 | 경기 | 충청 | 경상 | 전라 | 제주 | 부산 | 수도권 | 강원 | test |
|---|---|---|---|---|---|---|---|---|---|---|
| 1998 | 150 | 200 | -10 | 10 | 5 | 1 | 5 | 350 | 10.0 | NaN |
| 1999 | 180 | 240 | 3 | 20 | 6 | 1 | 5 | 420 | NaN | NaN |
| 2000 | 300 | 450 | -13 | 30 | 7 | 1 | 2 | 750 | -10.0 | NaN |
| 2001 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.0 | 0.0 |
| 2002 | -90 | 49 | 3 | -77 | -34 | 7 | 11 | 21 | 83.0 | 50.0 |
dict로 추가:{'key':'value', ...}>'column':'value', ...: column별 value 지정 가능
pop_sample.loc[2003] = {'서울':10, '경기':20, '충청':40, '경상':21, '전라':37,
'제주':103, '부산':28, '수도권':30, '강원':15, 'test':0}
pop_sample
| location | 서울 | 경기 | 충청 | 경상 | 전라 | 제주 | 부산 | 수도권 | 강원 | test |
|---|---|---|---|---|---|---|---|---|---|---|
| 1998 | 150 | 200 | -10 | 10 | 5 | 1 | 5 | 350 | 10.0 | NaN |
| 1999 | 180 | 240 | 3 | 20 | 6 | 1 | 5 | 420 | NaN | NaN |
| 2000 | 300 | 450 | -13 | 30 | 7 | 1 | 2 | 750 | -10.0 | NaN |
| 2001 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.0 | 0.0 |
| 2002 | -90 | 49 | 3 | -77 | -34 | 7 | 11 | 21 | 83.0 | 50.0 |
| 2003 | 10 | 20 | 40 | 21 | 37 | 103 | 28 | 30 | 15.0 | 0.0 |
list로 추가
pop_sample.loc[2004] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
pop_sample
| location | 서울 | 경기 | 충청 | 경상 | 전라 | 제주 | 부산 | 수도권 | 강원 | test |
|---|---|---|---|---|---|---|---|---|---|---|
| 1998 | 150 | 200 | -10 | 10 | 5 | 1 | 5 | 350 | 10.0 | NaN |
| 1999 | 180 | 240 | 3 | 20 | 6 | 1 | 5 | 420 | NaN | NaN |
| 2000 | 300 | 450 | -13 | 30 | 7 | 1 | 2 | 750 | -10.0 | NaN |
| 2001 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.0 | 0.0 |
| 2002 | -90 | 49 | 3 | -77 | -34 | 7 | 11 | 21 | 83.0 | 50.0 |
| 2003 | 10 | 20 | 40 | 21 | 37 | 103 | 28 | 30 | 15.0 | 0.0 |
| 2004 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9.0 | 0.0 |
row 추가
- operation between rows
pop_sample.loc[2005] = pop_sample.loc[2002] * pop_sample.loc[2004]
pop_sample
| location | 서울 | 경기 | 충청 | 경상 | 전라 | 제주 | 부산 | 수도권 | 강원 | test |
|---|---|---|---|---|---|---|---|---|---|---|
| 1998 | 150.0 | 200.0 | -10.0 | 10.0 | 5.0 | 1.0 | 5.0 | 350.0 | 10.0 | NaN |
| 1999 | 180.0 | 240.0 | 3.0 | 20.0 | 6.0 | 1.0 | 5.0 | 420.0 | NaN | NaN |
| 2000 | 300.0 | 450.0 | -13.0 | 30.0 | 7.0 | 1.0 | 2.0 | 750.0 | -10.0 | NaN |
| 2001 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
| 2002 | -90.0 | 49.0 | 3.0 | -77.0 | -34.0 | 7.0 | 11.0 | 21.0 | 83.0 | 50.0 |
| 2003 | 10.0 | 20.0 | 40.0 | 21.0 | 37.0 | 103.0 | 28.0 | 30.0 | 15.0 | 0.0 |
| 2004 | 1.0 | 2.0 | 3.0 | 4.0 | 5.0 | 6.0 | 7.0 | 8.0 | 9.0 | 0.0 |
| 2005 | -90.0 | 98.0 | 9.0 | -308.0 | -170.0 | 42.0 | 77.0 | 168.0 | 747.0 | 0.0 |
6. row, columns 삭제¶
columns 삭제
del+ column indexingdf['column']df.drop('column', axis=1)df.drop(columns='column')
row 삭제
df.drop(idx): default:axis=0
pop_sample
| location | 서울 | 경기 | 충청 | 경상 | 전라 | 제주 | 부산 | 수도권 | 강원 | test |
|---|---|---|---|---|---|---|---|---|---|---|
| 1998 | 150.0 | 200.0 | -10.0 | 10.0 | 5.0 | 1.0 | 5.0 | 350.0 | 10.0 | NaN |
| 1999 | 180.0 | 240.0 | 3.0 | 20.0 | 6.0 | 1.0 | 5.0 | 420.0 | NaN | NaN |
| 2000 | 300.0 | 450.0 | -13.0 | 30.0 | 7.0 | 1.0 | 2.0 | 750.0 | -10.0 | NaN |
| 2001 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
| 2002 | -90.0 | 49.0 | 3.0 | -77.0 | -34.0 | 7.0 | 11.0 | 21.0 | 83.0 | 50.0 |
| 2003 | 10.0 | 20.0 | 40.0 | 21.0 | 37.0 | 103.0 | 28.0 | 30.0 | 15.0 | 0.0 |
| 2004 | 1.0 | 2.0 | 3.0 | 4.0 | 5.0 | 6.0 | 7.0 | 8.0 | 9.0 | 0.0 |
| 2005 | -90.0 | 98.0 | 9.0 | -308.0 | -170.0 | 42.0 | 77.0 | 168.0 | 747.0 | 0.0 |
del pop_sample['test']
pop_sample
| location | 서울 | 경기 | 충청 | 경상 | 전라 | 제주 | 부산 | 수도권 | 강원 |
|---|---|---|---|---|---|---|---|---|---|
| 1998 | 150.0 | 200.0 | -10.0 | 10.0 | 5.0 | 1.0 | 5.0 | 350.0 | 10.0 |
| 1999 | 180.0 | 240.0 | 3.0 | 20.0 | 6.0 | 1.0 | 5.0 | 420.0 | NaN |
| 2000 | 300.0 | 450.0 | -13.0 | 30.0 | 7.0 | 1.0 | 2.0 | 750.0 | -10.0 |
| 2001 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
| 2002 | -90.0 | 49.0 | 3.0 | -77.0 | -34.0 | 7.0 | 11.0 | 21.0 | 83.0 |
| 2003 | 10.0 | 20.0 | 40.0 | 21.0 | 37.0 | 103.0 | 28.0 | 30.0 | 15.0 |
| 2004 | 1.0 | 2.0 | 3.0 | 4.0 | 5.0 | 6.0 | 7.0 | 8.0 | 9.0 |
| 2005 | -90.0 | 98.0 | 9.0 | -308.0 | -170.0 | 42.0 | 77.0 | 168.0 | 747.0 |
columns 삭제
df.drop('column', axis=1)- 원본 반영 X,
inplace=Trueoptional parameter 설정 필요
- 원본 반영 X,
pop_sample.drop('강원', axis=1)
| location | 서울 | 경기 | 충청 | 경상 | 전라 | 제주 | 부산 | 수도권 |
|---|---|---|---|---|---|---|---|---|
| 1998 | 150.0 | 200.0 | -10.0 | 10.0 | 5.0 | 1.0 | 5.0 | 350.0 |
| 1999 | 180.0 | 240.0 | 3.0 | 20.0 | 6.0 | 1.0 | 5.0 | 420.0 |
| 2000 | 300.0 | 450.0 | -13.0 | 30.0 | 7.0 | 1.0 | 2.0 | 750.0 |
| 2001 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
| 2002 | -90.0 | 49.0 | 3.0 | -77.0 | -34.0 | 7.0 | 11.0 | 21.0 |
| 2003 | 10.0 | 20.0 | 40.0 | 21.0 | 37.0 | 103.0 | 28.0 | 30.0 |
| 2004 | 1.0 | 2.0 | 3.0 | 4.0 | 5.0 | 6.0 | 7.0 | 8.0 |
| 2005 | -90.0 | 98.0 | 9.0 | -308.0 | -170.0 | 42.0 | 77.0 | 168.0 |
pop_sample
| location | 서울 | 경기 | 충청 | 경상 | 전라 | 제주 | 부산 | 수도권 | 강원 |
|---|---|---|---|---|---|---|---|---|---|
| 1998 | 150.0 | 200.0 | -10.0 | 10.0 | 5.0 | 1.0 | 5.0 | 350.0 | 10.0 |
| 1999 | 180.0 | 240.0 | 3.0 | 20.0 | 6.0 | 1.0 | 5.0 | 420.0 | NaN |
| 2000 | 300.0 | 450.0 | -13.0 | 30.0 | 7.0 | 1.0 | 2.0 | 750.0 | -10.0 |
| 2001 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
| 2002 | -90.0 | 49.0 | 3.0 | -77.0 | -34.0 | 7.0 | 11.0 | 21.0 | 83.0 |
| 2003 | 10.0 | 20.0 | 40.0 | 21.0 | 37.0 | 103.0 | 28.0 | 30.0 | 15.0 |
| 2004 | 1.0 | 2.0 | 3.0 | 4.0 | 5.0 | 6.0 | 7.0 | 8.0 | 9.0 |
| 2005 | -90.0 | 98.0 | 9.0 | -308.0 | -170.0 | 42.0 | 77.0 | 168.0 | 747.0 |
columns 삭제
df.drop(columns='column')- 원본 영향 X, optional parameter
inplace=True설정 필요
- 원본 영향 X, optional parameter
pop_sample.drop(columns='강원', inplace=True)
pop_sample
| location | 서울 | 경기 | 충청 | 경상 | 전라 | 제주 | 부산 | 수도권 |
|---|---|---|---|---|---|---|---|---|
| 1998 | 150.0 | 200.0 | -10.0 | 10.0 | 5.0 | 1.0 | 5.0 | 350.0 |
| 1999 | 180.0 | 240.0 | 3.0 | 20.0 | 6.0 | 1.0 | 5.0 | 420.0 |
| 2000 | 300.0 | 450.0 | -13.0 | 30.0 | 7.0 | 1.0 | 2.0 | 750.0 |
| 2001 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
| 2002 | -90.0 | 49.0 | 3.0 | -77.0 | -34.0 | 7.0 | 11.0 | 21.0 |
| 2003 | 10.0 | 20.0 | 40.0 | 21.0 | 37.0 | 103.0 | 28.0 | 30.0 |
| 2004 | 1.0 | 2.0 | 3.0 | 4.0 | 5.0 | 6.0 | 7.0 | 8.0 |
| 2005 | -90.0 | 98.0 | 9.0 | -308.0 | -170.0 | 42.0 | 77.0 | 168.0 |
pop_sample
| location | 서울 | 경기 | 충청 | 경상 | 전라 | 제주 | 부산 | 수도권 |
|---|---|---|---|---|---|---|---|---|
| 1998 | 150.0 | 200.0 | -10.0 | 10.0 | 5.0 | 1.0 | 5.0 | 350.0 |
| 1999 | 180.0 | 240.0 | 3.0 | 20.0 | 6.0 | 1.0 | 5.0 | 420.0 |
| 2000 | 300.0 | 450.0 | -13.0 | 30.0 | 7.0 | 1.0 | 2.0 | 750.0 |
| 2001 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
| 2002 | -90.0 | 49.0 | 3.0 | -77.0 | -34.0 | 7.0 | 11.0 | 21.0 |
| 2003 | 10.0 | 20.0 | 40.0 | 21.0 | 37.0 | 103.0 | 28.0 | 30.0 |
| 2004 | 1.0 | 2.0 | 3.0 | 4.0 | 5.0 | 6.0 | 7.0 | 8.0 |
| 2005 | -90.0 | 98.0 | 9.0 | -308.0 | -170.0 | 42.0 | 77.0 | 168.0 |
pop_sample.drop(2004, inplace=True)
pop_sample
| location | 서울 | 경기 | 충청 | 경상 | 전라 | 제주 | 부산 | 수도권 |
|---|---|---|---|---|---|---|---|---|
| 1998 | 150.0 | 200.0 | -10.0 | 10.0 | 5.0 | 1.0 | 5.0 | 350.0 |
| 1999 | 180.0 | 240.0 | 3.0 | 20.0 | 6.0 | 1.0 | 5.0 | 420.0 |
| 2000 | 300.0 | 450.0 | -13.0 | 30.0 | 7.0 | 1.0 | 2.0 | 750.0 |
| 2001 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
| 2002 | -90.0 | 49.0 | 3.0 | -77.0 | -34.0 | 7.0 | 11.0 | 21.0 |
| 2003 | 10.0 | 20.0 | 40.0 | 21.0 | 37.0 | 103.0 | 28.0 | 30.0 |
| 2005 | -90.0 | 98.0 | 9.0 | -308.0 | -170.0 | 42.0 | 77.0 | 168.0 |
pop_sample.drop(['제주', '수도권'], axis=1, inplace=True)
pop_sample
| location | 서울 | 경기 | 충청 | 경상 | 전라 | 부산 |
|---|---|---|---|---|---|---|
| 1998 | 150.0 | 200.0 | -10.0 | 10.0 | 5.0 | 5.0 |
| 1999 | 180.0 | 240.0 | 3.0 | 20.0 | 6.0 | 5.0 |
| 2000 | 300.0 | 450.0 | -13.0 | 30.0 | 7.0 | 2.0 |
| 2001 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
| 2002 | -90.0 | 49.0 | 3.0 | -77.0 | -34.0 | 11.0 |
| 2003 | 10.0 | 20.0 | 40.0 | 21.0 | 37.0 | 28.0 |
| 2005 | -90.0 | 98.0 | 9.0 | -308.0 | -170.0 | 77.0 |
pop_sample.drop([2003, 2005], inplace=True)
pop_sample
| location | 서울 | 경기 | 충청 | 경상 | 전라 | 부산 |
|---|---|---|---|---|---|---|
| 1998 | 150.0 | 200.0 | -10.0 | 10.0 | 5.0 | 5.0 |
| 1999 | 180.0 | 240.0 | 3.0 | 20.0 | 6.0 | 5.0 |
| 2000 | 300.0 | 450.0 | -13.0 | 30.0 | 7.0 | 2.0 |
| 2001 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
| 2002 | -90.0 | 49.0 | 3.0 | -77.0 | -34.0 | 11.0 |
7. DataFrame 사이의 산술 연산 (Operation)¶
Operation between
DataFrameandDataFramecolumns, row sorted
columns index, row index 기준 operation 수행
common index 아닐 경우:
NaN반환fill_value=value:NaN이 아닌 값으로 대체 가능
Operator 종류
add :
+,df1.add(df2)subtract :
-,df1.sub(df2)multiply:
*,df1.mul(df2)divide:
/,df1.div(df2)get int division:
//,df1.floordiv(df2)modulo:
%,df1.mod(df2)
op_df = pd.DataFrame(np.random.randint(1, 10, 9).reshape(3, 3),
index=list('abc'),
columns=['서울', '경기', '인천'])
op_df
| 서울 | 경기 | 인천 | |
|---|---|---|---|
| a | 1 | 6 | 6 |
| b | 3 | 7 | 2 |
| c | 5 | 4 | 7 |
nd_df = pd.DataFrame(np.random.randint(1, 10, (20)).reshape(4, 5),
columns=['서울', '경기', '인천', '대전', '부산'],
index=list('abcd'))
nd_df
| 서울 | 경기 | 인천 | 대전 | 부산 | |
|---|---|---|---|---|---|
| a | 4 | 9 | 4 | 8 | 5 |
| b | 5 | 5 | 9 | 2 | 3 |
| c | 5 | 7 | 6 | 9 | 3 |
| d | 8 | 8 | 2 | 5 | 9 |
add:
+,df1.add(df2)- result: common index(row, column)만 정상 연산, 아닌 부분은
NaN반환`
- result: common index(row, column)만 정상 연산, 아닌 부분은
op_df + nd_df
| 경기 | 대전 | 부산 | 서울 | 인천 | |
|---|---|---|---|---|---|
| a | 15.0 | NaN | NaN | 5.0 | 10.0 |
| b | 12.0 | NaN | NaN | 8.0 | 11.0 |
| c | 11.0 | NaN | NaN | 10.0 | 13.0 |
| d | NaN | NaN | NaN | NaN | NaN |
fill_value=valueoptional parameter: 없는 data를value로 채움
op_df.add(nd_df, fill_value=0)
| 경기 | 대전 | 부산 | 서울 | 인천 | |
|---|---|---|---|---|---|
| a | 15.0 | 8.0 | 5.0 | 5.0 | 10.0 |
| b | 12.0 | 2.0 | 3.0 | 8.0 | 11.0 |
| c | 11.0 | 9.0 | 3.0 | 10.0 | 13.0 |
| d | 8.0 | 5.0 | 9.0 | 8.0 | 2.0 |
- subtract:
-,df1.sub(df2)
op_df - nd_df
| 경기 | 대전 | 부산 | 서울 | 인천 | |
|---|---|---|---|---|---|
| a | -3.0 | NaN | NaN | -3.0 | 2.0 |
| b | 2.0 | NaN | NaN | -2.0 | -7.0 |
| c | -3.0 | NaN | NaN | 0.0 | 1.0 |
| d | NaN | NaN | NaN | NaN | NaN |
op_df.sub(nd_df, fill_value=0)
| 경기 | 대전 | 부산 | 서울 | 인천 | |
|---|---|---|---|---|---|
| a | -3.0 | -8.0 | -5.0 | -3.0 | 2.0 |
| b | 2.0 | -2.0 | -3.0 | -2.0 | -7.0 |
| c | -3.0 | -9.0 | -3.0 | 0.0 | 1.0 |
| d | -8.0 | -5.0 | -9.0 | -8.0 | -2.0 |
- 특정 row끼리 연산
op_df.loc[['a', 'c']] - nd_df.loc[['a', 'c']]
| 경기 | 대전 | 부산 | 서울 | 인천 | |
|---|---|---|---|---|---|
| a | -3 | NaN | NaN | -3 | 2 |
| c | -3 | NaN | NaN | 0 | 1 |
- multiply:
*,df1.mul(df2)
op_df * nd_df
| 경기 | 대전 | 부산 | 서울 | 인천 | |
|---|---|---|---|---|---|
| a | 54.0 | NaN | NaN | 4.0 | 24.0 |
| b | 35.0 | NaN | NaN | 15.0 | 18.0 |
| c | 28.0 | NaN | NaN | 25.0 | 42.0 |
| d | NaN | NaN | NaN | NaN | NaN |
op_df.mul(nd_df, fill_value=1)
| 경기 | 대전 | 부산 | 서울 | 인천 | |
|---|---|---|---|---|---|
| a | 54.0 | 8.0 | 5.0 | 4.0 | 24.0 |
| b | 35.0 | 2.0 | 3.0 | 15.0 | 18.0 |
| c | 28.0 | 9.0 | 3.0 | 25.0 | 42.0 |
| d | 8.0 | 5.0 | 9.0 | 8.0 | 2.0 |
- divide:
/,df1.div(df2)
op_df / nd_df
| 경기 | 대전 | 부산 | 서울 | 인천 | |
|---|---|---|---|---|---|
| a | 0.666667 | NaN | NaN | 0.25 | 1.500000 |
| b | 1.400000 | NaN | NaN | 0.60 | 0.222222 |
| c | 0.571429 | NaN | NaN | 1.00 | 1.166667 |
| d | NaN | NaN | NaN | NaN | NaN |
op_df.div(nd_df, fill_value=1)
| 경기 | 대전 | 부산 | 서울 | 인천 | |
|---|---|---|---|---|---|
| a | 0.666667 | 0.125000 | 0.200000 | 0.250 | 1.500000 |
| b | 1.400000 | 0.500000 | 0.333333 | 0.600 | 0.222222 |
| c | 0.571429 | 0.111111 | 0.333333 | 1.000 | 1.166667 |
| d | 0.125000 | 0.200000 | 0.111111 | 0.125 | 0.500000 |
- int division:
//,df1.floordiv(df2)
op_df.floordiv(nd_df, fill_value=1)
| 경기 | 대전 | 부산 | 서울 | 인천 | |
|---|---|---|---|---|---|
| a | 0.0 | 0.0 | 0.0 | 0.0 | 1.0 |
| b | 1.0 | 0.0 | 0.0 | 0.0 | 0.0 |
| c | 0.0 | 0.0 | 0.0 | 1.0 | 1.0 |
| d | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
- modulo:
%,df1.mod(df2)
op_df.mod(nd_df, fill_value=1)
| 경기 | 대전 | 부산 | 서울 | 인천 | |
|---|---|---|---|---|---|
| a | 6.0 | 1.0 | 1.0 | 1.0 | 2.0 |
| b | 2.0 | 1.0 | 1.0 | 3.0 | 2.0 |
| c | 4.0 | 1.0 | 1.0 | 0.0 | 1.0 |
| d | 1.0 | 1.0 | 1.0 | 1.0 | 1.0 |
8. DataFrame과 Series 사이의 산술 연산
Operation between DataFrame and Series
Basic logic:
Seriesobject의row label index,DataFrameobject의column label indexmapping > BroadCasting 발생common
label index아닐 때:NaN값 반환연산 method 수행:
axis=axisparameter > 연산 적용할 축 지정 (0: row, 1: column)
Operator 종류
add :
+,.add()subtract :
-,.sub()multifly :
*,.mul()
my_df = pd.DataFrame(np.arange(12).reshape(3, 4),
index=[2010, 2011, 2012],
columns=list('abcd'))
my_df
| a | b | c | d | |
|---|---|---|---|---|
| 2010 | 0 | 1 | 2 | 3 |
| 2011 | 4 | 5 | 6 | 7 |
| 2012 | 8 | 9 | 10 | 11 |
my_sr = my_df.iloc[0]
my_sr
a 0 b 1 c 2 d 3 Name: 2010, dtype: int32
Operation between
DataFrameandSeries: commonindex name> mapping DataFrame object
column label indexand Series objectrow label index>
Seriesobjectname,DataFrame의row index name상관 없음> 원본 반영X, 반환된 결과 저장 필요
my_df + my_sr
| a | b | c | d | |
|---|---|---|---|---|
| 2010 | 0 | 2 | 4 | 6 |
| 2011 | 4 | 6 | 8 | 10 |
| 2012 | 8 | 10 | 12 | 14 |
my_df
| a | b | c | d | |
|---|---|---|---|---|
| 2010 | 0 | 1 | 2 | 3 |
| 2011 | 4 | 5 | 6 | 7 |
| 2012 | 8 | 9 | 10 | 11 |
my_sr = my_sr.rename(2020)
print(my_sr)
my_df + my_sr
a 0 b 1 c 2 d 3 Name: 2020, dtype: int32
| a | b | c | d | |
|---|---|---|---|---|
| 2010 | 0 | 2 | 4 | 6 |
| 2011 | 4 | 6 | 8 | 10 |
| 2012 | 8 | 10 | 12 | 14 |
Operation between
DataFrameandSeries- mapping DataFrame object
column label indexand Series objectrow label index
- mapping DataFrame object
zr_df = pd.DataFrame(np.zeros(20).reshape(4,5),
columns=list('abcde'))
zr_df
| a | b | c | d | e | |
|---|---|---|---|---|---|
| 0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
| 1 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
| 2 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
| 3 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
no_sr = pd.Series(np.arange(5))
no_sr
0 0 1 1 2 2 3 3 4 4 dtype: int32
zr_df.sub(no_sr)
| a | b | c | d | e | 0 | 1 | 2 | 3 | 4 | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN |
| 1 | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN |
| 2 | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN |
| 3 | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN |
Operation between
DataFrameandSeriesinaxis=0> mapping DataFrame
row label indexand Seriesrow label index
zr_df.sub(no_sr, axis=0)
| a | b | c | d | e | |
|---|---|---|---|---|---|
| 0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
| 1 | -1.0 | -1.0 | -1.0 | -1.0 | -1.0 |
| 2 | -2.0 | -2.0 | -2.0 | -2.0 | -2.0 |
| 3 | -3.0 | -3.0 | -3.0 | -3.0 | -3.0 |
| 4 | NaN | NaN | NaN | NaN | NaN |
- DataFrame
column label index에 없는row label index를 가진 Series와의 연산
defi_sr = pd.Series([3, 3, 3], index=list('ace'))
defi_sr
a 3 c 3 e 3 dtype: int64
my_df
| a | b | c | d | |
|---|---|---|---|---|
| 2010 | 0 | 1 | 2 | 3 |
| 2011 | 4 | 5 | 6 | 7 |
| 2012 | 8 | 9 | 10 | 11 |
Uncommon index (unable mapping) > return
NaNOperation between
SeriesandDataFrame:fill_value=valueparameter 사용 불가
my_df + defi_sr
| a | b | c | d | e | |
|---|---|---|---|---|---|
| 2010 | 3.0 | NaN | 5.0 | NaN | NaN |
| 2011 | 7.0 | NaN | 9.0 | NaN | NaN |
| 2012 | 11.0 | NaN | 13.0 | NaN | NaN |
my_df.add(defi_sr)
| a | b | c | d | e | |
|---|---|---|---|---|---|
| 2010 | 3.0 | NaN | 5.0 | NaN | NaN |
| 2011 | 7.0 | NaN | 9.0 | NaN | NaN |
| 2012 | 11.0 | NaN | 13.0 | NaN | NaN |
my_df.add(defi_sr, fill_value=0)
--------------------------------------------------------------------------- NotImplementedError Traceback (most recent call last) ~\AppData\Local\Temp\ipykernel_11052\1613751262.py in <module> ----> 1 my_df.add(defi_sr, fill_value=0) ~\anaconda3\lib\site-packages\pandas\core\ops\__init__.py in f(self, other, axis, level, fill_value) 427 # TODO: We could allow this in cases where we end up going 428 # through the DataFrame path --> 429 raise NotImplementedError(f"fill_value {fill_value} not supported.") 430 431 axis = self._get_axis_number(axis) if axis is not None else 1 NotImplementedError: fill_value 0 not supported.
'CS & DS > Numpy & Pandas' 카테고리의 다른 글
| Pandas Data pre-processing 판다스 데이터 전처리 (0) | 2022.11.12 |
|---|---|
| Pandas Data Loading 판다스 데이터 적재 (0) | 2022.11.05 |
| Pandas Series 판다스 시리즈 (0) | 2022.11.03 |
| Numpy array Manipulation 넘파이 배열 변형 (0) | 2022.11.02 |
| Numpy Operation 넘파이 연산 (0) | 2022.10.30 |