Изменить тип данных столбца или серии Pandas
Серии - это одномерный помеченный массив, способный хранить данные типа integer, string, float, python и т. Д. Метки осей вместе называются индексами.
Давайте посмотрим на программу для изменения типа данных столбца или серии в Pandas Dataframe.
Метод 1. Использование метода DataFrame.astype ().
Мы можем передать любой тип данных Python, Numpy или Pandas, чтобы изменить все столбцы фрейма данных на этот тип, или мы можем передать словарь, имеющий имена столбцов в качестве ключей и тип данных в качестве значений, чтобы изменить тип выбранных столбцов.
Syntax: DataFrame.astype(dtype, copy = True, errors = ’raise’, **kwargs)
Return: casted : type of caller
Let’s see the examples:
Example 1: The Data type of the column is changed to “str” object.
Python3
# importing the pandas libraryimport pandas as pd # creating a DataFramedf = pd.DataFrame({"srNo": [1, 2, 3], "Name": ["Geeks", "for", "Geeks"], "id": [111, 222, 333]})# show the dataframeprint(df) # show the datatypesprint(df.dtypes) |
Выход:

Now, changing the dataframe data types to string.
Python3
# changing the dataframe # data types to stringdf = df.astype(str) # show the data types # of dataframedf.dtypes |
Выход :

Example 2: Now, let us change the data type of the “id” column from “int” to “str”. We create a dictionary and specify the column name with the desired data type.
Python3
# importing the pandas libraryimport pandas as pd # creating a DataFramedf = pd.DataFrame({"No": [1, 2, 3], "Name": ["Geeks", "for", "Geeks"], "id": [111, 222, 333]})# show the dataframeprint(df) # show the datatypesprint(df.dtypes) |
Выход:

Now, change the data type of ‘id’ column to string.
Python3
# creating a dictionary # with column name and data typedata_types_dict = {"id": str} # we will change the data type # of id column to str by giving# the dict to the astype methoddf = df.astype(data_types_dict) # checking the data types# using df.dtypes methoddf.dtypes |
Выход:

Example 3: Convert the data type of “grade” column from “float” to “int”.
Python3
# import pandas libraryimport pandas as pd # dictionaryresult_data = {"name": ["Alia", "Rima", "Kate", "John", "Emma", "Misa", "Matt"], "grade": [13.5, 7.1, 11.5, 3.77, 8.21, 21.22, 17.5], "qualify": ["yes", "no", "yes", "no", "no", "yes", "yes"]} # create a dataframedf = pd.DataFrame(result_data) # show the dataframeprint(df) #show the datatypesprint(df.dtypes) |
Выход:

Now, we convert the data type of “grade” column from “float” to “int”.
Python3
# convert data type of grade column # into integerdf.grade = df.grade.astype(int) # show the dataframeprint(df) # show the datatypesprint(df.dtypes) |
Выход:

Метод 2: Использование метода Dataframe.apply ().
Мы можем передать pandas.to_numeric, pandas.to_datetime и pandas.to_timedelta в качестве аргумента функции apply (), чтобы изменить тип данных одного или нескольких столбцов на numeric, datetime и timedelta соответственно.
Syntax: Dataframe/Series.apply(func, convert_dtype=True, args=())
Return: Dataframe/Series after applied function/operation.
Посмотрим на пример:
Example: Convert the data type of “B” column from “string” to “int”.
Python3
# importing pandas as pd import pandas as pd # sample dataframe df = pd.DataFrame({ "A": ["a", "b", "c", "d", "e"], "B": [12, 22, 35, "47", "55"], "C": [1.1, "2.1", 3.0, "4.1", "5.1"] }) # show the dataframeprint(df) # show the data types# of all columnsdf.dtypes |
Выход:

Now, we convert the datatype of column “B” into an “int” type.
Python3
# using apply method df[["B"]] = df[["B"]].apply(pd.to_numeric) # show the data types# of all columnsdf.dtypes |
Выход:

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.