λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
studyπŸ“š/python

[python/파이썬] 데이터 μ „μ²˜λ¦¬ - νƒ€μž… λ³€ν™˜ dtype, astype(), to_datetime()

by μŠ€λ‹ 2022. 7. 26.

νƒ€μž… λ³€ν™˜

  • 데이터 생성
import pandas as pd

df = pd.DataFrame({'판맀일' : ['5/11/21', '5/12/21', '5/13/21', '5/14/21', '5/15/21'],
                   'νŒλ§€λŸ‰' : ['10', '15', '20', '25', '30'], '방문자수' : ['10', '-', '17', '23', '25'], 
                   '기온' : ['24.1', '24.3', '24.8', '25', '25.4']})
df

  • dtype : 데이터 νƒ€μž… 확인
df.dtypes

판맀일 object
νŒλ§€λŸ‰ object
방문자수 object
기온 object
dtype: object

df['νŒλ§€λŸ‰ 보정'] = df['νŒλ§€λŸ‰'] + 1

  • astype(νƒ€μž…) : λ°μ΄ν„°ν”„λ ˆμž„ νƒ€μž… 전체 ν•œκΊΌλ²ˆμ— λ°”κΎΈκΈ°
  • astype({'column' : 'type'}) : μ›ν•˜λŠ” 컬럼만 νƒ€μž… λ°”κΎΈκΈ°

-문제 : νŒλ§€λŸ‰μ„ μ •μˆ˜ ν˜•νƒœλ‘œ λ³€ν™˜ν•˜κΈ°

df.astype({'νŒλ§€λŸ‰' : 'int'})

df.dtypes

판맀일 object
νŒλ§€λŸ‰ object
방문자수 object
기온 object
dtype: object

df = df.astype({'νŒλ§€λŸ‰' : 'int'})
df.dtypes

판맀일 object
νŒλ§€λŸ‰ int64
방문자수 object
기온 object
dtype: object

df['νŒλ§€λŸ‰ 보정'] = df['νŒλ§€λŸ‰'] + 1
df

-문제 : 방문자수λ₯Ό 숫자 νƒ€μž…μœΌλ‘œ λ³€ν˜•ν•˜κΈ°

df.astype({'방문자수' : 'int'})

pd.to_numeric(df['방문자수'])

pd.to_numeric(df['방문자수'], errors = 'coerce')

0 10.0
1 NaN
2 17.0
3 23.0
4 25.0
Name: 방문자수, dtype: float64

df.dtypes

판맀일 object
νŒλ§€λŸ‰ int64
방문자수 object
기온 object
νŒλ§€λŸ‰ 보정 int64
dtype: object

df['방문자수'] = pd.to_numeric(df['방문자수'], errors = 'coerce')
df.dtypes

판맀일 object
νŒλ§€λŸ‰ int64
방문자수 float64
기온 object
νŒλ§€λŸ‰ 보정 int64
dtype: object

df

df = df.astype({'방문자수' : 'int'})

df.fillna(0, inplace = True)
df

df = df.astype({'방문자수' : 'int'})
df.dtypes

판맀일 object
νŒλ§€λŸ‰ int64
방문자수 int64
기온 object
νŒλ§€λŸ‰ 보정 int64
dtype: object

df

  • to_datetime(param, format="") : μ£Όμ–΄μ§„ 인수λ₯Ό datetime 으둜 λ³€ν™˜

-문제 : νŒλ§€μΌμ„ datetime 의 ν˜•νƒœλ‘œ λ°”κΎΈκΈ°

df['판맀일'] = pd.to_datetime(df['판맀일'], format="%m/%d/%y")
df

df.dtypes

판맀일  datetime64[ns]
νŒλ§€λŸ‰  int64
방문자수  int64
기온  object
νŒλ§€λŸ‰ 보정 int64
dtype:  object

λŒ“κΈ€