반응형
Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | ||||
| 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- Excel
- GIT
- Redshift
- 파이썬
- django
- list
- google apps script
- gas
- numpy
- array
- dataframe
- Github
- Python
- SQL
- matplotlib
- Kotlin
- PostgreSQL
- math
- hive
- Java
- string
- PANDAS
- Google Excel
- c#
- Tkinter
- Presto
- Apache
- PySpark
- Google Spreadsheet
Archives
- Today
- Total
달나라 노트
Python Pandas : dtypes (column의 data type 출력, column data type 확인) 본문
Python/Python Pandas
Python Pandas : dtypes (column의 data type 출력, column data type 확인)
CosmosProject 2025. 9. 28. 03:32728x90
반응형
Dataframe에 있는 column들의 data type을 확인하는 방법은 여러 가지가 있습니다만
이번에는 내가 원하는 컬럼의 data type만을 확인하고 싶을 때에는 dtypes를 사용하면 됩니다.
Syntax
dataFrame.dtypes
dtypes는 위처럼 그냥 dataframe에 적용만 해주면 됩니다.
예시를 봐봅시다.
import pandas as pd
# 1 dataframe 생성
df = pd.DataFrame({
'col1': [1, 2, 3, 4, 5],
'col2': ['a', 'b', 'c', 'd', 'e'],
'col3': [1.0, 2.5, 3.9, 0.4, 2.0]
})
# 2 dataframe 출력
print(df)
# 3 col2, col3의 data type 출력
# col2는 string data를 담고 있으므로 object로 표시됨
# col3은 실수 데이터를 담고 있으므로 float으로 표시됨
print(df.loc[:, ['col2', 'col3']].dtypes)
-- Result
col1 col2 col3
0 1 a 1.0
1 2 b 2.5
2 3 c 3.9
3 4 d 0.4
4 5 e 2.0
col2 object
col3 float64
dtype: object
위처럼 정말 간단하게 dataframe에 dtype를 전달하면 됩니다.
dtypes를 이용할 때 loc를 사용하고 싶지 않으면 그냥 아래처럼 이중 대괄호를 사용하여 간단하게 dataframe을 명시하면서 dtypes를 실행시킬 수 있습니다.
import pandas as pd
# 1 dataframe 생성
df = pd.DataFrame({
'col1': [1, 2, 3, 4, 5],
'col2': ['a', 'b', 'c', 'd', 'e'],
'col3': [1.0, 2.5, 3.9, 0.4, 2.0]
})
# 2 dataframe 출력
print(df)
# 3 col2, col3의 data type 출력 (간단하게 이중괄호 사용)
# col2는 string data를 담고 있으므로 object로 표시됨
# col3은 실수 데이터를 담고 있으므로 float으로 표시됨
print(df[['col2', 'col3']].dtypes)
-- Result
col1 col2 col3
0 1 a 1.0
1 2 b 2.5
2 3 c 3.9
3 4 d 0.4
4 5 e 2.0
col2 object
col3 float64
dtype: object
dtypes를 이용할 때 column별 data type 정보를 별도의 dataframe으로 구성하고 tabulate같은 함수와 같이 사용하면
좀 더 가독성 있게 column별 data type을 표시해줄 수 있습니다.
import pandas as pd
from tabulate import tabulate
# 1 dataframe 생성
df = pd.DataFrame({
'col1': [1, 2, 3, 4, 5],
'col2': ['a', 'b', 'c', 'd', 'e'],
'col3': [1.0, 2.5, 3.9, 0.4, 2.0]
})
# 2 dataframe 출력
print(df)
# 3 col2, col3의 data type 정보를 dataframe으로 구성
df_dtype_info = pd.DataFrame(df[['col2', 'col3']].dtypes).reset_index(drop=False, inplace=False)
# 4 명확하게 하기 위해 컬럼 이름 설정
df_dtype_info.columns = ['column_name', 'dtype']
# 5 tabulate과 함께 가독성 있게 표시
print(tabulate(df_dtype_info, headers='keys', tablefmt='psql', showindex=True, stralign='center'))
-- Result
col1 col2 col3
0 1 a 1.0
1 2 b 2.5
2 3 c 3.9
3 4 d 0.4
4 5 e 2.0
+----+---------------+---------+
| | column_name | dtype |
|----+---------------+---------|
| 0 | col2 | object |
| 1 | col3 | float64 |
+----+---------------+---------+
728x90
반응형
'Python > Python Pandas' 카테고리의 다른 글
Comments
