Python/pandas

pandas, pandas 기초 문법 통합정리

euncheol kim 2022. 1. 14. 22:59

Goal

pandas의 기본 문법에 대해서 이해한다.

Update

지속적 업데이트 예정
[ 초기 업데이트 2022-01-14 ]
[ 마지막 업데이트 2022-01-14 ]

참고사항

이번 게시글은 jupyter notebook으로 작성되었습니다.
해당 포스팅은 모바일 웹 레이아웃에 문제가 있는 것으로 확인했습니다. 가급적 모바일이 아닌 PC로 보실 것을 권장합니다.

게시글에 오류, 수정, 추가, 개선이 필요할 경우 지적해주시면 감사하겠습니다.


1. pandas basics

Table of Contents

  1. pandas
    • 1.1 pandas 개념
    • 1.2 pandas 데이터 구조
  2. pandas 사용하기
  3. pandas Series

1. pandas

Table of Contents

1.1 pandas 개념

Table of Contents

  • pandas는 파이썬에서 사용할 수 있는 데이터분석 라이브러리입니다.
  • 행과 열로 이루어진 데이터 객체를 만들어 다룰 수 있습니다.
  • 대용량의 데이터들을 처리하는데 매우 편리한 도구입니다.
  • 뒤에서 설명할 pandas의 Series와 DataFrame은 numpy와 달리 index를 가집니다.

1.2 pandas 데이터 구조

Table of Contents

  • Pandas는 3종류의 데이터 구조를 제공합니다. (Series, DataFrame, Panel)
  • 주로 Series와 DataFrame을 사용하며 각각 1차원, 2차원임을 기억합니다.

pd_DataFrame구조

  • DataFrame은 Row, Column, Series들로 구성되어 있습니다.
    • row는 DataFrame의 각 행을 의미합니다.
    • column은 DataFrame의 각 열을 의미합니다.
    • 하나의 column은 Series입니다.
    • 하나의 column이 Series이라함은 Series가 모여 DataFrame을 이룬다고 할 수 있습니다.

2. pandas 사용하기

Table of Contents

In [ ]:

# pandas 사용하기
import pandas as pd

3. pandas Series

Table of Contents

3.1 pandas Series 개념

Table of Contents

  • pandas Series의 데이터 타입은 Series타입입니다.
  • pandas Series는 각 data마다 index를 가집니다.
    • numpy와 pandas Series의 차이점

3.2 pandas Series 생성하기, 활용하기

Table of Contents

3.2.1 pd.Serise()에 list를 넘겨 생성하기, 데이터 타입 확인하기

- Serise data 생성 후
    - 1열 : index
    - 2열 : Series의 데이터
    - 데이터 타입 : Series데이터

In [ ]:

# pandas Series, list로 데이터 생성하기
ex_01 = pd.Series(["가", "나", "다", "라"]) 
ex_02 = pd.Series(["1", "2", "3", "4"])
ex_03 = pd.Series([1, 2, 3, 4])

print(ex_01, sep="") # Series 출력
print("ex_01의 type확인 : ",type(ex_01)) # type 확인
print("*"*55)

print(ex_02, sep="") # Series출력
print("ex_02의 type확인 : ",type(ex_02)) # type 확인
print("*"*55)

print(ex_03, sep="") # Series출력
print("ex_03의 type확인 : ",type(ex_03)) # type 확인
0    가
1    나
2    다
3    라
dtype: object
ex_01의 type확인 :  <class 'pandas.core.series.Series'>
*******************************************************
0    1
1    2
2    3
3    4
dtype: object
ex_02의 type확인 :  <class 'pandas.core.series.Series'>
*******************************************************
0    1
1    2
2    3
3    4
dtype: int64
ex_03의 type확인 :  <class 'pandas.core.series.Series'>

3.2.2 pd.Series()에 dictionary를 넘겨 생성하기

  • dictionary로 Series를 생성하면 key값이 index로, value값이 Series의 data로 들어간다

In [ ]:

dic = {"철수": 100, 
       "영희": 75, 
       "민수" : 80}

class_score = pd.Series(dic)
print(class_score)
철수    100
영희     75
민수     80
dtype: int64

3.2.3 pd.Series()의 value값 변경하기

  • Series 데이터를 생성후에도 value를 변경이 가능하다.
    • indexing과 slicing
      • indexing과 slicing 모두 index의 위치로 변경하는 방법과 index 이름으로 변경하는 방법이 있습니다.
      • 이름으로 변경 하는 방법은 index의 이름을 넣어주면 되고
      • 위치로 변경 하는 방법은 index의 위치를 넣어주면 됩니다. 단, index위치는 0번째부터 시작합니다.
  • iloc와 loc 기법이 있으나 DataFrame에서 다시 언급하겠습니다.

※ Serise, indexing, slicing 참고 포스팅

Bing, "[Python] 03. pandas Series 인덱싱(Indexing),슬라이싱(Slicing) : boolean indexing,loc()과 iloc() 차이 예제", https://makeit.tistory.com/15,

In [ ]:

key_school = ["1반", "2반", "3반","4반","5반","6반"]
value_count = [17, 15, 27, 21, 30, 12]

series_school = pd.Series(data = value_count, index = key_school)
print(series_school, "\n")
1반    17
2반    15
3반    27
4반    21
5반    30
6반    12
dtype: int64 

In [ ]:

# value값 변경(indexing)
# (1) 인덱스 이름을 이용한 인덱싱
series_school["1반"] = 111 # value값 변경 -> indexing
print("Indexing으로 변경 후(1) : ")
print(series_school, "\n")

# (2) 인덱스 위치를 이용한 인덱싱
series_school[1] = 222 # value값 변경 -> indexing
print("Indexing으로 변경 후(2) : ")
print(series_school, "\n")
Indexing으로 변경 후(1) : 
1반    111
2반     15
3반     27
4반     21
5반     30
6반     12
dtype: int64 

Indexing으로 변경 후(2) : 
1반    111
2반    222
3반     27
4반     21
5반     30
6반     12
dtype: int64 

In [ ]:

# value값 변경(slicing)
# (1) 인덱스 이름을 이용한 슬라이싱
series_school["3반" : "4반"] = 777
print("Slicing으로 변경 후(1) : ")
print(series_school, "\n")

# (1) 인덱스 위치를 이용한 슬라이싱
series_school[4 : 6] = 999
print("Slicing으로 변경 후(2) : ")
print(series_school, "\n")
Slicing으로 변경 후(1) : 
1반    111
2반    222
3반    777
4반    777
5반     30
6반     12
dtype: int64 

Slicing으로 변경 후(2) : 
1반    111
2반    222
3반    777
4반    777
5반    999
6반    999
dtype: int64