Jin's Dev Story

[Python] Pandase(판다스) 본문

Programming Language/Python

[Python] Pandase(판다스)

woojin._. 2024. 6. 13. 09:01

Pandas

  • 쉽고 직관적인 관계형 또는 분류된 데이터로 작업할 수 있도록 설계된 빠르고 유연하며 표현이 풍부한 데이터 구조를 제공하는 Python 패키지
  • 데이터 분석을 위한 핵심라이브러리로써 고유한 자료구조인 Series와 DataFrame을 활용하여 빅데이터 분석에 엄청난 수준의 퍼포먼스를 발휘함
  • Series(index 있음)와 DataFrame은 numpy(선형대수)(index 없음)의 1차원 2차원 array와 유사함
  • 간단한 차이점은 array에 index가 있는 형태

Pandas로 할 수 있는 기능

  • 빠른 Indexing, Slicing, Sorting 하는 기능
  • 두 데이터 간의 Join(행, 열 방향) 기능
  • 데이터의 피봇팅 및 그룹핑
  • 데이터의 통계 및 시각화 기능
  • 외부 데이터를 입력 받아 Pandas 자료구조로 저장 및 출력

데이터 검색 시 사용하는 라이브러리 → import os

os.listdir('.')

→ . 하나만 있는 경우 현재 어떤 파일이 있는지 확인하는 것

데이터 불러오기 - read_csv

  • utf-8의 csv로 저장된 파일이어야 데이터를 불러올 수 있음
# pandas의 read_csv -> 데이터 불러오기
df = pd.read_csv(friend_src, encoding='utf-8')
  • head()
    • 5개의 데이터만 읽어
# head() 데이터를 읽어보기
df.head()

데이터 저장하기 - to_csv

  • new_friend_src 위치에 new_friend_src 라는 이름으로 df를 저장하겠다라는 의미
  • index=False 꼭 하기
    • 넣지 않은 경우 Unnamed와 같은 불필요한 데이터가 보여짐

# index=False 꼭 하기(필요없는 데이터는 안가져오게 하려고)
df.to_csv(new_friend_src,index=False,encoding='utf-8')

→ os.listdir()로 파일이 생성되었나 확인하기

중복 데이터 확인 - duplicated()

# 중복 데이터 삭제
# 중복된 row를 확인하는 법
abalone_df.duplicated()
abalone_df.duplicated().sum()
  • 불린 형태로 나옴
  • true 값 세는 방법 → 뒤에 .sum() 붙이기

합치다 - concat()

# 중복 예제 생성을 위해서 가상으로 중복데이터 생성

new_abalone = abalone_df.iloc[[0]]
new_abalone_df = pd.concat([abalone_df, new_abalone], axis=0)
new_abalone_df
  • new_abalone_df = pd.concat([abalone_df, new_abalone], axis=0)
  • abalone_df과 new_abalone을 행 형태로 합칠 것이다.

  • 열 기준
# 두 개의 DataFrame 합치기
# 가상 abalone 1개 row 데이터 생성 및 결합
one_abalone_df = abalone_df.iloc[[0]]
pd.concat([abalone_df, one_abalone_df], axis=0)

  • 행 기준
# 전체 행의 성별에 대해
one_abalone_df = abalone_df.iloc[:, [0]]
pd.concat([abalone_df, one_abalone_df], axis=1)

중복 데이터 값 순서 변환(첫 번째 ↔ 마지막)

new_abalone_df.duplicated(keep='last')

중복 데이터 삭제 - new_abalone_df.drop_duplicates()

# 중복 데이터(row 삭제)
new_abalone_df = new_abalone_df.drop_duplicates()

'Programming Language > Python' 카테고리의 다른 글

[Python] DataFrame  (0) 2024.06.13
[Python] iloc와 loc  (0) 2024.06.13
[Python] 시각화할 때 한글 깨지는 경우  (0) 2024.06.13
[Python] Numpy(넘파이)  (0) 2024.06.13
[Python] 정규 표현식(RegExp)  (0) 2024.06.13