AI 그게 뭔데
끄적끄적 개발일지
AI 그게 뭔데
전체 방문자
오늘
어제
  • 분류 전체보기 (342)
    • 논문 (5)
    • DL(Deep-Learning) (34)
      • 개념 (14)
      • Python 기초 (14)
      • Tensorflow (6)
      • Pytorch (0)
    • NLP (10)
    • OpenCV (53)
    • DevOps (10)
      • AWS (2)
      • Docker & Kubernetes (4)
      • Spark (3)
      • SQL (1)
    • MacOS (1)
    • React-Native (2)
    • BI (3)
      • GA(Google Analytics) (3)
      • Tableau (0)
    • 알고리즘 (221)
      • 백준 (76)
      • 프로그래머스 (108)
      • 기타 알고리즘 (37)

인기 글

태그

  • 프로그래머스
  • 파이썬
  • LEVEL2
  • 이코테
  • Python
  • 연습문제
  • OpenCV
  • level1
  • 백준
  • 알고리즘

최근 글

hELLO · Designed By 정상우.
AI 그게 뭔데

끄적끄적 개발일지

DL(Deep-Learning)/Python 기초

[Python] DataFrame 데이터 타입 변환하기

2022. 1. 27. 11:26

pnadas DataFrame에서 데이터 타입을 변경해보자.

 

데이터 타입 확인하기

df.dtypes
더보기
user_id        int64
session_id     int64
timestamp     object
app_name      object
event_type    object
dtype: object

 

 

데이터 타입 전체 변경하기

df.astype('float', errors='ignore')
더보기
user_id       float64
session_id    float64
timestamp      object
app_name       object
event_type     object
dtype: object

 

 

원하는 컬럼만 데이터 타입 변경하기

df = df.astype({'session_id':'int'})
더보기
user_id       float64
session_id      int64
timestamp      object
app_name       object
event_type     object
dtype: object

 

딕셔너리를 이용하여 컬럼명과 데이터 타입을 매개변수로 전달하면 해당 컬럼의 데이터 타입만 변경 가능하다.

 

 

숫자로 데이터 타입 변경하기

import pandas as pd

df = pd.read_csv('data.csv')
pd.to_numeric(df, errors='coerce')

 

to_numeric()을 사용하면 숫자가 아닌 값을 NaN으로 만들 수 있다.

errors = ' ignore/raise/coerce' 3가지 종류가 있다.

 

  • errors = 'ignore' -> 만약 숫자로 변경할 수 없는 데이터라면 숫자로 변경하지 않고 원본 데이터를 그대로 반환
  • errors = 'coerce' -> 만약 숫자로 변경할 수 없는 데이터라면 기존 데이터를 지우고 NaN으로 설정하여 반환
  • errors = 'raise' -> 만약 숫자로 변경할 수 없는 데이터라면 에러를 일으키며 코드를 중단

 

날짜 형식으로 타입 변경하기

df.loc[:,'timestamp'] = pd.to_datetime(df['timestamp'])
더보기
user_id       float64
session_id      int64
timestamp      datetime64[ns]
app_name       object
event_type     object
dtype: object

 

'DL(Deep-Learning) > Python 기초' 카테고리의 다른 글

[Python] Convert JPG to PNG (feat. PIL)  (0) 2022.01.27
Google Colab 런타임 연결 유지 & 출력 삭제  (0) 2022.01.26
[Python] 파일 이름 변경하기  (0) 2022.01.26
DataFrame 합치기2 (concat, merge, join)  (0) 2022.01.26
DataFrame 합치기1 (concat, merge, join)  (0) 2022.01.26
    AI 그게 뭔데
    AI 그게 뭔데
    공부와 개발 그리고 AI가 약간 첨가된 흔적 남기기

    티스토리툴바