YOGYUI

pandas - 데이터프레임 데이터형(dtype) 확인 본문

Software/Python

pandas - 데이터프레임 데이터형(dtype) 확인

요겨 2021. 9. 21. 05:37
반응형

 

pandas 데이터프레임(DataFrame) 객체의 열(column)의 데이터형을 가져오는 방법을 알아보자

(get data type of columns in dataframe)

 

예시를 위해 int, float, str, bool, datetime 데이터를 가진 데이터프레임을 만들어준다

from datetime import datetime
import pandas as pd

array = list()
array.append({'A': 1, 'B': 1.0, 'C': '1', 'D': True, 'E': datetime(2021, 9, 1)})
array.append({'A': 2, 'B': 1.1, 'C': '2', 'D': False, 'E': datetime(2021, 9, 2)})
array.append({'A': 3, 'B': 1.2, 'C': '3', 'D': True, 'E': datetime(2021, 9, 3)})
df = pd.DataFrame(array)
In [1]: df
Out[1]:
   A    B  C      D          E
0  1  1.0  1   True 2021-09-01
1  2  1.1  2  False 2021-09-02
2  3  1.2  3   True 2021-09-03

1. info 메서드

데이터프레임 객체에 info 메서드를 호출하면 데이터프레임의 레코드(행) 수, 칼럼 수, 각 칼럼별 데이터타입, 메모리 사용량 등 전반적인 정보를 알 수 있다

In [2]: df.info()
Out[2]:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 5 columns):
 #   Column  Non-Null Count  Dtype         
---  ------  --------------  -----         
 0   A       3 non-null      int64         
 1   B       3 non-null      float64       
 2   C       3 non-null      object        
 3   D       3 non-null      bool          
 4   E       3 non-null      datetime64[ns]
dtypes: bool(1), datetime64[ns](1), float64(1), int64(1), object(1)
memory usage: 227.0+ bytes

2. dtypes  멤버변수

데이터프레임 객체는 dtypes 이름을 가진 멤버변수를 갖고 있다 (type=pandas Series)

In [3]: df.dtypes
Out[3]:
A             int64
B           float64
C            object
D              bool
E    datetime64[ns]
dtype: object

In [4]: type(df.dtypes)
Out[4]: <class 'pandas.core.series.Series'>

간단하게 칼럼의 데이터형만을 알고 싶을때 사용하면 편하다

 

이와 유사하게, 각 칼럼별 Series 객체도 dtype 멤버변수를 갖고 있다

In [5]: df['A'].dtype
Out[5]: dtype('int64')

다음과 같이 전체 칼럼에 대한 dtype 호출도 고려할 수 있다

In [6]: for cl in df.columns:
            print(f'{cl}: {df[cl].dtype}')
Out[6]:
A: int64
B: float64
C: object
D: bool
E: datetime64[ns]

 

[참고]

https://stackoverflow.com/questions/40353079/pandas-how-to-check-dtype-for-all-columns-in-a-dataframe

반응형
Comments