판다스(Pandas) 기초 - Data Frame 개념 및 사용법
판다스(Pandas)란?
- Pandas는 Python Data Analysis Library의 약어이고, Python을 활용해 데이터 분석을 하기 위해서 사용하는 패키지입니다.
- 판다스 데이터 프레임 (Pandas DataFrame)을 활용하면 데이터를 표(Table)형태로 처리할 수 있어 수집된 데이터의 전처리 등 각종 데이터 핸들링을 쉽고 편하게 할 수 있습니다.
데이터프레임(DataFrame)이란?
- 판다스 데이터프레임(Pandas DataFrame)은 다양한 데이터 타입을 이용하여 만들 수 있습니다. (list, dictionary, series, ndarray 등)
- 개념적으로 데이터 프레임은 Series들을 하나의 열로 취급한 집합이라고 볼 수 있습니다.
- 데이터를 표의 형태로 처리하는 자료구조로, 보통 RDB 환경에서 SQL로 테이블을 컨트롤 할 수 있는 수준의 기능들이 상당 부분 데이터프레임에 구현되어 있습니다.
1. DataFrame 생성 방법
- 다양한 데이터 타입을 이용하여 만들 수 있지만, 두가지 방법을 사용해 보겠습니다.
- List 이용
# 데이터 프레임 생성 (list) listFrame = pd.DataFrame([[1,2,3], [4,5,6],[7,8,9]]) print('--------------리스트 데이터 프레임--------------') print(listFrame) ''' --------------리스트 데이터 프레임-------------- 0 1 2 0 1 2 3 1 4 5 6 2 7 8 9 '''
- Dictionary 이용
# 데이터 프레임 생성 (dictionary) data = { 'age' : [20, 30, 40], 'height' : [160, 170, 180], 'weight' : [60, 70, 80] } indexName = ['python', 'pandas', 'dataframe'] dictionaryFrame = pd.DataFrame(data, index=indexName) print('\n--------------딕셔너리 데이터 프레임--------------') print(dictionaryFrame) ''' --------------딕셔너리 데이터 프레임-------------- age height weight python 20 160 60 pandas 30 170 70 dataframe 40 180 80 '''
- List 이용
2. DataFrame 조회 방법
- 열(Column) 조회
# 데이터 프레임 조회 # 열(Column) 조회 print('\n--------------dictionary 열 조회--------------') print('-------딕셔너리 열 조회 방법 1-------') print(dictionaryFrame['age']) print('-------딕셔너리 열 조회 방법 2-------') print(dictionaryFrame.age) # 특정 열 조회 print('\n--------------dictionary 특정 열 조회--------------') print('-------딕셔너리 특정 열 조회 방법 1-------') print(dictionaryFrame['height']['python']) print('-------딕셔너리 특정 열 조회 방법 2-------') print(dictionaryFrame.height['python']) ''' --------------dictionary 열 조회-------------- -------딕셔너리 열 조회 방법 1------- python 20 pandas 30 dataframe 40 Name: age, dtype: int64 -------딕셔너리 열 조회 방법 2------- python 20 pandas 30 dataframe 40 Name: age, dtype: int64 --------------dictionary 특정 열 조회-------------- -------딕셔너리 특정 열 조회 방법 1------- 160 -------딕셔너리 특정 열 조회 방법 2------- 160 '''
- 행(Row) 조회 : 행 조회는 열 조회와 조금 다르게 loc와 iloc를 사용해서 조회할 수 있습니다.
# 데이터 프레임 조회 # 행(Row) 조회 print('\n--------------dictionary 행 조회--------------') print('-------딕셔너리 행 조회 방법 1-------') print(dictionaryFrame.loc[['python']]) print('-------딕셔너리 행 조회 방법 2-------') print(dictionaryFrame.iloc[0]) ''' --------------dictionary 행 조회-------------- -------딕셔너리 행 조회 방법 1------- age height weight python 20 160 60 -------딕셔너리 행 조회 방법 2------- age 20 height 160 weight 60 Name: python, dtype: int64 '''
3. DataFrame 수정 방법
- 열(Column) 추가 : 먼저 컬럼을 추가하고 추가된 컬럼에 대한 값을 추가해주면 됩니다. (컬럼만 추가 시 NaN)
# 데이터 프레임 수정 print('\n--------------딕셔너리 데이터 프레임 수정--------------') frame_add_col = pd.DataFrame(dictionaryFrame, columns=['age', 'height', 'weight', 'num']) print('\n--------------딕셔너리 데이터 프레임 열 추가--------------') print(frame_add_col) print('--------------추가된 열에 대한 값 추가--------------') frame_add_col['num'] = [1, 2, 3] print(frame_add_col) ''' --------------딕셔너리 데이터 프레임 수정-------------- --------------딕셔너리 데이터 프레임 열 추가-------------- age height weight num python 20 160 60 NaN pandas 30 170 70 NaN dataframe 40 180 80 NaN --------------추가된 열에 대한 값 추가-------------- age height weight num python 20 160 60 1 pandas 30 170 70 2 dataframe 40 180 80 3 '''
- 행(Row) 추가
# 데이터 프레임 수정 print('\n--------------딕셔너리 데이터 프레임 행 추가--------------') frame_add_index = frame_add_col.copy() frame_add_index.loc['pycharm'] = [50, 190, 90, 4] print(frame_add_index) ''' --------------딕셔너리 데이터 프레임 행 추가-------------- age height weight num python 20 160 60 1 pandas 30 170 70 2 dataframe 40 180 80 3 pycharm 50 190 90 4 '''
- 행, 열 삭제 : 옵션에 axis 값은 행이면 0, 열이면 1로 지정하고 inplace = True로 해줘야 기존 프레임을 사용하여 삭제합니다.
# 데이터 프레임 수정 print('\n--------------딕셔너리 데이터 프레임 행, 열 삭제--------------') print('원본 데이터 : ') print(frame_add_index) print('--------------열 삭제--------------') frame_add_index.drop('num', axis=1, inplace=True) print(frame_add_index) print('--------------행 삭제--------------') frame_add_index.drop('pycharm', axis=0, inplace=True) print(frame_add_index) ''' --------------딕셔너리 데이터 프레임 행, 열 삭제-------------- 원본 데이터 : age height weight num python 20 160 60 1 pandas 30 170 70 2 dataframe 40 180 80 3 pycharm 50 190 90 4 --------------열 삭제-------------- age height weight python 20 160 60 pandas 30 170 70 dataframe 40 180 80 pycharm 50 190 90 --------------행 삭제-------------- age height weight python 20 160 60 pandas 30 170 70 dataframe 40 180 80 '''
전체코드
더보기
더보기
import pandas as pd
# pip install pandas를 입력하여 pandas 패키지 다운받기
# 데이터 프레임 생성 (list)
listFrame = pd.DataFrame([[1,2,3], [4,5,6],[7,8,9]])
print('--------------리스트 데이터 프레임--------------')
print(listFrame)
# 데이터 프레임 생성 (dictionary)
data = {
'age' : [20, 30, 40],
'height' : [160, 170, 180],
'weight' : [60, 70, 80]
}
indexName = ['python', 'pandas', 'dataframe']
dictionaryFrame = pd.DataFrame(data, index=indexName)
print('\n--------------딕셔너리 데이터 프레임--------------')
print(dictionaryFrame)
# 데이터 프레임 조회
# 열(Column) 조회
print('\n--------------dictionary 열 조회--------------')
print('-------딕셔너리 열 조회 방법 1-------')
print(dictionaryFrame['age'])
print('-------딕셔너리 열 조회 방법 2-------')
print(dictionaryFrame.age)
# 특정 열 조회
print('\n--------------dictionary 특정 열 조회--------------')
print('-------딕셔너리 특정 열 조회 방법 1-------')
print(dictionaryFrame['height']['python'])
print('-------딕셔너리 특정 열 조회 방법 2-------')
print(dictionaryFrame.height['python'])
# 행(Row) 조회
print('\n--------------dictionary 행 조회--------------')
print('-------딕셔너리 행 조회 방법 1-------')
print(dictionaryFrame.loc[['python']])
print('-------딕셔너리 행 조회 방법 2-------')
print(dictionaryFrame.iloc[0])
# 데이터 프레임 수정
print('\n--------------딕셔너리 데이터 프레임 수정--------------')
frame_add_col = pd.DataFrame(dictionaryFrame, columns=['age', 'height', 'weight', 'num'])
print('\n--------------딕셔너리 데이터 프레임 열 추가--------------')
print(frame_add_col)
print('--------------추가된 열에 대한 값 추가--------------')
frame_add_col['num'] = [1, 2, 3]
print(frame_add_col)
print('\n--------------딕셔너리 데이터 프레임 행 추가--------------')
frame_add_index = frame_add_col.copy()
frame_add_index.loc['pycharm'] = [50, 190, 90, 4]
print(frame_add_index)
print('\n--------------딕셔너리 데이터 프레임 행, 열 삭제--------------')
print('원본 데이터 : ')
print(frame_add_index)
print('--------------열 삭제--------------')
frame_add_index.drop('num', axis=1, inplace=True)
print(frame_add_index)
print('--------------행 삭제--------------')
frame_add_index.drop('pycharm', axis=0, inplace=True)
print(frame_add_index)
'''
--------------리스트 데이터 프레임--------------
0 1 2
0 1 2 3
1 4 5 6
2 7 8 9
--------------딕셔너리 데이터 프레임--------------
age height weight
python 20 160 60
pandas 30 170 70
dataframe 40 180 80
--------------dictionary 열 조회--------------
-------딕셔너리 열 조회 방법 1-------
python 20
pandas 30
dataframe 40
Name: age, dtype: int64
-------딕셔너리 열 조회 방법 2-------
python 20
pandas 30
dataframe 40
Name: age, dtype: int64
--------------dictionary 특정 열 조회--------------
-------딕셔너리 특정 열 조회 방법 1-------
160
-------딕셔너리 특정 열 조회 방법 2-------
160
--------------dictionary 행 조회--------------
-------딕셔너리 행 조회 방법 1-------
age height weight
python 20 160 60
-------딕셔너리 행 조회 방법 2-------
age 20
height 160
weight 60
Name: python, dtype: int64
--------------딕셔너리 데이터 프레임 수정--------------
--------------딕셔너리 데이터 프레임 열 추가--------------
age height weight num
python 20 160 60 NaN
pandas 30 170 70 NaN
dataframe 40 180 80 NaN
--------------추가된 열에 대한 값 추가--------------
age height weight num
python 20 160 60 1
pandas 30 170 70 2
dataframe 40 180 80 3
--------------딕셔너리 데이터 프레임 행 추가--------------
age height weight num
python 20 160 60 1
pandas 30 170 70 2
dataframe 40 180 80 3
pycharm 50 190 90 4
--------------딕셔너리 데이터 프레임 행, 열 삭제--------------
원본 데이터 :
age height weight num
python 20 160 60 1
pandas 30 170 70 2
dataframe 40 180 80 3
pycharm 50 190 90 4
--------------열 삭제--------------
age height weight
python 20 160 60
pandas 30 170 70
dataframe 40 180 80
pycharm 50 190 90
--------------행 삭제--------------
age height weight
python 20 160 60
pandas 30 170 70
dataframe 40 180 80
'''
'Python' 카테고리의 다른 글
[Python] - 파이참 프로젝트 디렉토리 사라짐 현상 (0) | 2024.10.21 |
---|---|
[Python] - TypeError: 'set' object is not subscriptable (0) | 2024.10.20 |
[Python] - 파이썬을 이용한 더미데이터 만들기 (1) | 2024.10.01 |
[Python] - 파이썬 pep8 코드 스타일 (4) | 2024.09.26 |
[Python] - 워드 클라우드 사용하기 (4) | 2024.09.25 |