pandas.DataFrame.astype#
Use a str, numpy.dtype, pandas.ExtensionDtype or Python type to cast entire pandas object to the same type. Alternatively, use a mapping, e.g. , where col is a column label and dtype is a numpy.dtype or Python type to cast one or more of the DataFrame’s columns to column-specific types.
copy bool, default True
Return a copy when copy=True (be very careful setting copy=False as changes to values then may propagate to other pandas objects).
errors , default ‘raise’
Control raising of exceptions on invalid data for provided dtype.
- raise : allow exceptions to be raised
- ignore : suppress exceptions. On error return original object.
Convert argument to datetime.
Convert argument to timedelta.
Convert argument to a numeric type.
Cast a numpy array to a specified type.
Changed in version 2.0.0: Using astype to convert from timezone-naive dtype to timezone-aware dtype will raise an exception. Use Series.dt.tz_localize() instead.
>>> 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
>>> 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, int32): [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]
>>> 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]
pandas.Series.astype#
Use a str, numpy.dtype, pandas.ExtensionDtype or Python type to cast entire pandas object to the same type. Alternatively, use a mapping, e.g. , where col is a column label and dtype is a numpy.dtype or Python type to cast one or more of the DataFrame’s columns to column-specific types.
copy bool, default True
Return a copy when copy=True (be very careful setting copy=False as changes to values then may propagate to other pandas objects).
errors , default ‘raise’
Control raising of exceptions on invalid data for provided dtype.
- raise : allow exceptions to be raised
- ignore : suppress exceptions. On error return original object.
Convert argument to datetime.
Convert argument to timedelta.
Convert argument to a numeric type.
Cast a numpy array to a specified type.
Changed in version 2.0.0: Using astype to convert from timezone-naive dtype to timezone-aware dtype will raise an exception. Use Series.dt.tz_localize() instead.
>>> 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
>>> 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, int32): [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]
>>> 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]
Как преобразовать столбцы Pandas DataFrame в строки
Часто вы можете захотеть преобразовать один или несколько столбцов в кадре данных pandas в строки. К счастью, это легко сделать с помощью встроенной функции pandas astype(str) .
В этом руководстве показано несколько примеров использования этой функции.
Пример 1: преобразование одного столбца DataFrame в строку
Предположим, у нас есть следующие Pandas DataFrame:
import pandas as pd #create DataFrame df = pd.DataFrame() #view DataFrame df player points assists 0 A 25 5 1 B 20 7 2 C 14 7 3 D 16 8 4 E 27 11
Мы можем определить тип данных каждого столбца с помощью dtypes:
df.dtypes player object points int64 assists int64 dtype: object
Мы видим, что столбец «игрок» представляет собой строку, а два других столбца «очки» и «ассисты» — целые числа.
Мы можем преобразовать столбец «точки» в строку, просто используя astype(str) следующим образом:
df['points'] = df['points'].astype( str )
Мы можем убедиться, что этот столбец теперь является строкой, еще раз используя dtypes:
df.dtypes player object points object assists int64 dtype: object
Пример 2. Преобразование нескольких столбцов DataFrame в строки
Мы можем преобразовать оба столбца «точки» и «ассисты» в строки, используя следующий синтаксис:
df[['points', 'assists']] = df[['points', 'assists']].astype( str )
И еще раз мы можем проверить, что это строки, используя dtypes:
df.dtypes player object points object assists object dtype: object
Пример 3: преобразование всего фрейма данных в строки
Наконец, мы можем преобразовать каждый столбец в DataFrame в строки, используя следующий синтаксис:
#convert every column to strings df = df.astype(str) #check data type of each column df.dtypes player object points object assists object dtype: object
Вы можете найти полную документацию по функции astype() здесь .