Pandas: dtype변경 (astype)

calico·2025년 11월 28일

Artificial Intelligence

목록 보기
130/143

https://wikidocs.net/151412

DataFrame.astype(dtype, copy=True, errors='raise')


  • astype 메서드는 열의 요소의 dtype을 변경하는함수 입니다.



사용법



df.astype(dtype, copy=True, errors='raies')
  • dtype : 변경할 type입니다.

  • copy : 사본을 생성할지 여부입니다.

    • False로 할 경우 원본 데이터의 값이 변경 될 경우 원본 데이터를 사용해 생성된 객체의 데이터도 변경되기 때문에 False의 선택은 신중해야합니다.
  • errors : {'raies', 'ignore'} : 변경불가시 오류를 발생시킬 여부입니다.

    • False로 하여 오류를 발생시키지 않으면, 변경불가능한 요소는 원래 dtype 그대로 보존됩니다.



예시


  • 먼저, 아래와 같이 기본적인 4x4 행렬을 만듭니다. col1int64, col2object, col3float64, col4booldtype을 가집니다.
col1 = [1, 2, 3, 4]
col2 = ['one', 'two', 'three', 'four']
col3 = [1.5, 2.5, 3.5, 4.5]
col4 = [True, False, False, True]
index = ['row1','row2','row3','row4']
df = pd.DataFrame(index=index, data={"col1": col1, "col2": col2, "col3": col3, "col4": col4})
print(df)
>>
      col1   col2  col3   col4
row1     1    one   1.5   True
row2     2    two   2.5  False
row3     3  three   3.5  False
row4     4   four   4.5   True

print(df.dtypes)
>>
col1      int64
col2     object
col3    float64
col4       bool
dtype: object



한 개의 열만 type 변경


  • 열의 dtype 변경 시 딕셔너리 형태로 {'열이름': '변경 dtype'}와 같이 입력해줍니다.

    • int64 였던 col1dtypeint32로 변경된 것을 확인할 수 있습니다.

df1 = df.astype({'col1':'int32'})
print(df1.dtypes)

>> 
col1      int32
col2     object
col3    float64
col4       bool
dtype: object



다수의 열의 dtype 변경


  • 다수의 열의 변경도 딕셔너리 형식을 이용하면 됩니다.

    • int64 였던 col1dtypeint32로 변경되고 float64였던 col3dtype의 값이 int64로 변경된 것을 확인할 수 있습니다.
df = df.astype({'col1': 'int32', 'col3': 'int64'})
print(df1.dtypes)
>>
col1     int32
col2    object
col3     int64
col4      bool
dtype: object



모든 열의 dtype 변경


  • 모든열의 변경을 하고자하는 경우 dtype 인수에 원하는 dtype을 입력해주는 것만으로도 가능합니다.

df1 = df.astype(dtype='int64')
print(df1.dtypes)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[6], line 10
      7 index = ['row1','row2','row3','row4']
      8 df = pd.DataFrame(index=index, data={"col1": col1, "col2": col2, "col3": col3, "col4": col4})
---> 10 df1 = df.astype(dtype='int64')
     11 print(df1)

File C:\ANN\env\Lib\site-packages\pandas\core\generic.py:6665, in NDFrame.astype(self, dtype, copy, errors)
   6659     results = [
   6660         ser.astype(dtype, copy=copy, errors=errors) for _, ser in self.items()
   6661     ]
   6663 else:
   6664     # else, only a single dtype is given
-> 6665     new_data = self._mgr.astype(dtype=dtype, copy=copy, errors=errors)
   6666     res = self._constructor_from_mgr(new_data, axes=new_data.axes)
   6667     return res.__finalize__(self, method="astype")

File C:\ANN\env\Lib\site-packages\pandas\core\internals\managers.py:449, in BaseBlockManager.astype(self, dtype, copy, errors)
    446 elif using_copy_on_write():
    447     copy = False
--> 449 return self.apply(
    450     "astype",
    451     dtype=dtype,
    452     copy=copy,
    453     errors=errors,
    454     using_cow=using_copy_on_write(),
    455 )

File C:\ANN\env\Lib\site-packages\pandas\core\internals\managers.py:363, in BaseBlockManager.apply(self, f, align_keys, **kwargs)
    361         applied = b.apply(f, **kwargs)
    362     else:
--> 363         applied = getattr(b, f)(**kwargs)
    364     result_blocks = extend_blocks(applied, result_blocks)
    366 out = type(self).from_blocks(result_blocks, self.axes)

File C:\ANN\env\Lib\site-packages\pandas\core\internals\blocks.py:784, in Block.astype(self, dtype, copy, errors, using_cow, squeeze)
    781         raise ValueError("Can not squeeze with more than one column.")
    782     values = values[0, :]  # type: ignore[call-overload]
--> 784 new_values = astype_array_safe(values, dtype, copy=copy, errors=errors)
    786 new_values = maybe_coerce_values(new_values)
    788 refs = None

File C:\ANN\env\Lib\site-packages\pandas\core\dtypes\astype.py:237, in astype_array_safe(values, dtype, copy, errors)
    234     dtype = dtype.numpy_dtype
    236 try:
--> 237     new_values = astype_array(values, dtype, copy=copy)
    238 except (ValueError, TypeError):
    239     # e.g. _astype_nansafe can fail on object-dtype of strings
    240     #  trying to convert to float
    241     if errors == "ignore":

File C:\ANN\env\Lib\site-packages\pandas\core\dtypes\astype.py:182, in astype_array(values, dtype, copy)
    179     values = values.astype(dtype, copy=copy)
    181 else:
--> 182     values = _astype_nansafe(values, dtype, copy=copy)
    184 # in pandas we don't store numpy str dtypes, so convert to object
    185 if isinstance(dtype, np.dtype) and issubclass(values.dtype.type, str):

File C:\ANN\env\Lib\site-packages\pandas\core\dtypes\astype.py:133, in _astype_nansafe(arr, dtype, copy, skipna)
    129     raise ValueError(msg)
    131 if copy or arr.dtype == object or dtype == object:
    132     # Explicit copy, or required since NumPy can't view from / to object.
--> 133     return arr.astype(dtype, copy=True)
    135 return arr.astype(dtype, copy=copy)

ValueError: invalid literal for int() with base 10: 'one'
  • col2 : object형식은 int64형태로 변경할 수가 없기 때문에 오류가 발생합니다.

    • 변경 가능한 열만 변경하려면, 아래와 같이 errors 인수를 기본값인 'raise' 에서 'ignore'로 변경하면 됩니다.
import pandas as pd

col1 = [1, 2, 3, 4]
col2 = ['one', 'two', 'three', 'four']
col3 = [1.5, 2.5, 3.5, 4.5]
col4 = [True, False, False, True]
index = ['row1','row2','row3','row4']
df = pd.DataFrame(index=index, data={"col1": col1, "col2": col2, "col3": col3, "col4": col4})

df1 = df.astype(dtype='int64', errors='ignore')
print(df1)

>>
col1   col2  col3  col4
row1     1    one     1     1
row2     2    two     2     0
row3     3  three     3     0
row4     4   four     4     1
profile
https://velog.io/@corone_hi/posts

0개의 댓글