DataFrame/Series.astype(dtype, copy=True, errors='raise')
지정한 dtype으로 pandas객체를 캐스팅한다.
매개변수Parameters
dtype 자료형data type, 또는 딕셔너리dict -> {column name : data type}
numpy.dtype 또는 Python type을 사용하여 pandas객체 전체를 같은 자료형으로 캐스팅한다.
딕셔너리로 캐스팅할 경우, {col: dtype, …}와 같이 키값col이 열 이름이고 dtype은 numpy.dtype 또는 Python type을 넣어 하나 또는 그 이상의 데이터프레임DataFrame의 열을 그 열에 지정된 자료형으로 캐스팅한다.
copy 불리언bool, default True
True일 경우, 객체를 복사하여 반환한다.
False일 경우, 객체를 참조복사하여 반환한다.
(copy=False로 설정하면 변경된 값이 다른 pandas객체로 전파될 수 있기 때문에 copy=False설정은 매우 주의해야 한다.)
>>> s1 = pd.Series([1, 2])
>>> s2 = s1.astype('int64', copy=False)
>>> s2[0] = 10
>>> s1 # note that s1[0] has changed too
0 10
1 2
dtype: int64
errors {‘raise’, ‘ignore’}, default ‘raise’
잘못된 dtype 값을 제공할 경우 예외가 발생한는 것을 조절한다.
- raise : 예외 발생을 허락한다.
- ignore : 예외 발생을 억제한다. 오류일 경우, 원본 객체를 반환한다.
반환하는 것
캐스팅된 동일한 객체( 데이터프레임DataFrame, 시리즈Series )
참조
astype()을 사용하여 timezone-naive(표준 시간대)자료형에서 timezone-aware(표준 시간대 인식) 자료형으로 변환하는 것은 지원하지 않게 될 것이고 1.3.0버전 이후로 예외가 발생할 것이다.
대신에 Series.dt.tz_localize() 을 사용하세요
예제
Create a DataFrame:
>>> d = {'col1': [1, 2], 'col2': [3, 4]}
>>> df = pd.DataFrame(data=d)
>>> df.dtypes
col1 int64
col2 int64
dtype: object
Cast all columns to int32:
>>> df.astype('int32').dtypes
col1 int32
col2 int32
dtype: object
Cast col1 to int32 using a dictionary:
>>> df.astype({'col1': 'int32'}).dtypes
col1 int32
col2 int64
dtype: object
Create a series:
>>> ser = pd.Series([1, 2], dtype='int32')
>>> ser
0 1
1 2
dtype: int32
>>> ser.astype('int64')
0 1
1 2
dtype: int64
Convert to categorical type:
>>> ser.astype('category')
0 1
1 2
dtype: category
Categories (2, int64): [1, 2]
여담
Convert to ordered categorical type with custom ordering:
>>> from pandas.api.types import CategoricalDtype
>>> cat_dtype = CategoricalDtype(
... categories=[2, 1], ordered=True)
>>> ser.astype(cat_dtype)
0 1
1 2
dtype: category
Categories (2, int64): [2 < 1]
Create a series of dates:
>>> ser_date = pd.Series(pd.date_range('20200101', periods=3))
>>> ser_date
0 2020-01-01
1 2020-01-02
2 2020-01-03
dtype: datetime64[ns]
P . S - One-character strings
Array-protocol type strings | dtype |
? | boolean |
b | (signed) byte |
B | unsigned byte |
i (소문자) | (signed) integer |
I (대문자) | unsigned integer |
f | floating-point |
c | complex-floating point |
M | datetime |
O | (Python) objects |
U | Unicode string |
예제
Create a DataFrame:
>>> d = {'col1': [1, 2], 'col2': [3, 4]}
>>> df = pd.DataFrame(data=d)
>>> df.dtypes
col1 int64
col2 int64
dtype: object
Cast all columns to int32:
>>> df.astype('i').dtypes
col1 int32
col2 int32
dtype: object
'Python 파이썬 > pandas' 카테고리의 다른 글
pandas ) 연속 데이터의 구간 분할 pandas.cut() (0) | 2022.04.20 |
---|---|
pandas ) 특정 요소 변경 replace() 함수 (0) | 2022.04.12 |
pandas ) 중복 데이터 처리 duplicated(), drop_duplicates() (0) | 2022.04.04 |
pandas ) 누락 데이터 처리 isnull(), dropna(), fillna(), replace() (0) | 2022.04.04 |
pandas ) 판다스 내장 그래프 도구 (0) | 2022.03.22 |
댓글